#!/usr/bin/env python
# -*- coding: utf-8 -*-

# aTrack - Python Elementary based APRS tool 
#
# Copyright (C) 2009 Petr Vaněk <vanous@penguin.cz>
# http://code.google.com/p/atrack/
#
# This file is part of aTrack.
#
# some parts of code (packet parsing, sending, receiving) was used from APRSXO project:
# Copyright (C) 2008, Jack Zielke <jack@linuxcoffee.com>
# Copyright (C) 2008, One Laptop Per Child
#
# Some ideas come from FAP - perl aprs parses, TODO: fill in details
#
# aTrack is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# aTracks is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
aTrack - Python Elementary based APRS tool 
"""

import sys, time, os, math, re

#import gtk, gobject
import elementary, ecore
import dbus, e_dbus
import ConfigParser
import socket
import random
import shutil

import httplib, urllib, urllib2

from string import maketrans
#----------do not edit unless you understand it-----------------
appversion=0.80
appname = "aTrack"

statusbuffer=[]
recvbuffer=4096
action = "stopit"

now_old = 0
now = 0
heading_old = 0
heading_now=0
force_send = 0	
__loc_last_location__= ""
connect_retry=10

delay_user = 30 #delay in seconds
delay=delay_user

bearing_change = 45
delay_minimum = 18

MAX_MSG_QUEUE=25
MAX_PER_CALL_QUEUE = 2
STATION_LIST={}

COURSE=""
aprs_path='APZATR'
aprs_data_type='=' #Position without timestamp (with APRS messaging)

DATA_DIR = "/usr/share/atrack/"

VIEW_STATION=""
POSITION=[0]
COURSE=""

mainloop = e_dbus.DBusEcoreMainLoop() 
dbus_system = dbus.SystemBus(mainloop=mainloop)
bus = dbus.SystemBus()

def save_config():
    config_file=open(__conffile__, 'wb')
    config.write(config_file)
    #win.show_main_page()


# debut output
#gps_data = "POS: " +  d_t_d(gps_lat) + " / " +  d_t_d(gps_long) + " / " +  gps_alt
#gps_data = "POS: " +  gps_lat + " / " +  gps_long + " / " +  gps_alt  
#print gps_data


# comment length is supposed to be 0 to 43 char. long-this is 53 char. but it works
packet = ''
# delay in seconds - 15 sec. is for testing - should be 20 to 30 min for fixed QTH
unique_packet_old=''
unique_packet_new=''

class getResources(object):
    def __init__(self):
        # request CPU device 
        try:
            print "requesting ousaged for CPU"
            usage_obj = bus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage') 
            self.usage_iface = dbus.Interface(usage_obj, 'org.freesmartphone.Usage') 
            self.usage_iface.RequestResource("CPU") 
        except:
            print "no CPU"

        # request Display device 
        try:
            print "get odeviced"
            display_obj = bus.get_object('org.freesmartphone.odeviced', '/org/freesmartphone/Device/Display/0') 
            self.display_iface = dbus.Interface(display_obj, 'org.freesmartphone.Device.Display') 
        except:
            print "no Display"

        # request Display device for dimming. This has to be phonefsod to keep dimming and Display united
        try:
            print "get phonefsod"
            phonefso_obj = bus.get_object('org.shr.phonefso', '/org/shr/phonefso/Usage') 
            self.phonefso_iface = dbus.Interface(phonefso_obj, 'org.shr.phonefso.Usage') 
        except:
            print "no Display"

        # request GPS device
        try:
            print "requesting GPS"
            usage_obj = bus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage') 
            self.usage_iface = dbus.Interface(usage_obj, 'org.freesmartphone.Usage') 
            self.usage_iface.RequestResource("GPS") 
        except:
            print "no gps"


        # get interface for Gypsy 

        try:
            print "get GYPSY"
            gypsy_obj = bus.get_object( 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy') 
            self.position_iface = dbus.Interface( gypsy_obj, 'org.freedesktop.Gypsy.Position')
            self.course_iface = dbus.Interface( gypsy_obj, 'org.freedesktop.Gypsy.Course')
            
            
        except:
            print "no gypsy"


        # get interface for GPRS

        try:
            print "get GSM (GPRS) object"
            self.gprs_obj = bus.get_object( 'org.freesmartphone.ogsmd', '/org/freesmartphone/GSM/Device') 
        except:
    	    print "no GSM/GPRS object"
    	try:
    	    print "get gprs iface"
            self.gprs_iface = dbus.Interface(self.gprs_obj, 'org.freesmartphone.GSM.PDP')
        except:
            print "no gprs"
        try:
    	    print "get gsm call iface"
    	    self.gsm_iface = dbus.Interface(self.gprs_obj, 'org.freesmartphone.GSM.Call')
    	except:
    	    print "no gsm call iface"


class Icon(elementary.Icon):
    def __init__(self, parent, image):
        elementary.Icon.__init__(self, parent)
        self.file_set(os.path.join(DATA_DIR, 'images', image))


class MainPage(object):
    def __init__(self, main):
        self.main = main

        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1) #expand
        self.box.size_hint_align_set(-1, -1) #expand
        self.box.show()

	global status_bar
        status_bar = elementary.Label(self.main.win)
        status_bar.label_set('<b>%s %s %s</>' % (appname, appversion, username))
        status_bar.size_hint_weight_set(0, 0)
        status_bar.size_hint_align_set(0.5, 0.5)
        self.box.pack_end(status_bar)
        status_bar.show()

        sc = elementary.Scroller(self.main.win)
        sc.bounce_set(False, True)
        sc.size_hint_weight_set(1.0, 1.0)
        sc.size_hint_align_set(-1.0, -1.0)
        self.box.pack_start(sc)
        sc.show()

        box = elementary.Box(self.main.win)
        box.size_hint_weight_set(1.0, 0)
        box.size_hint_align_set(-1, 0)
        sc.content_set(box)
        box.show()

        self.toggle = elementary.Toggle(self.main.win)
        self.toggle.label_set(" Track")
        self.toggle.icon_set(Icon(self.main.win, 'start-here.png'))
        self.toggle.states_labels_set("T: " + str(delay_user) + "s", "Not tracking")
        self.toggle.scale_set(1.5)
	self.toggle.size_hint_weight_set(1.0, 0)
	self.toggle.size_hint_align_set(-1, -1.0);
        self.toggle.callback_changed_add(self.toggleChanged)
        self.toggle.state_set(False)
	box.pack_end(self.toggle)
#        scroller.content_set(self.toggle)
	self.toggle.show()
	
	global toggle_con
        self.toggle_con = elementary.Toggle(self.main.win)
        self.toggle_con.label_set(" APRS")
        self.toggle_con.icon_set(Icon(self.main.win, 'atrack.png'))
        self.toggle_con.states_labels_set("connected", "Not connected")
	self.toggle_con.size_hint_weight_set(1.0, 0)
	self.toggle_con.size_hint_align_set(-1.0, -1.0)
        self.toggle_con.scale_set(1.5)
        self.toggle_con.callback_changed_add(self.toggle_conChanged)
        self.toggle_con.state_set(False)
	box.pack_end(self.toggle_con)
	self.toggle_con.show()

	global toggleg
        toggleg = elementary.Toggle(self.main.win)
        toggleg.label_set(" GPRS")
        toggleg.icon_set(Icon(self.main.win, 'system-software-update.png'))        
        toggleg.states_labels_set("Turn Gprs OFF" , "Turn Gprs ON")
        toggleg.scale_set(1.5)
	toggleg.size_hint_weight_set(1.0, 0)
	toggleg.size_hint_align_set(-1.0, -1.0)
        toggleg.callback_changed_add(self.togglegChanged)
        box.pack_end(toggleg)
        toggleg.show()

	global bt
	bt = elementary.Entry(self.main.win)
	bt.entry_set("")
	bt.scale_set(1)
	bt.line_wrap_set(1)
	bt.size_hint_weight_set(1.0, 1.0)
	bt.size_hint_align_set(-1.0, -1.0)
	bt.editable_set(False)
	bt.entry_set("")
	box.pack_end(bt)
        bt.show()

        subbox = elementary.Box(self.main.win)
        subbox.size_hint_weight_set(1.0, 0)
        subbox.horizontal_set(True)
        subbox.homogenous_set(True)
	subbox.size_hint_align_set(-1, -1)
        subbox.show()
        box.pack_end(subbox)
        
        
	global info
	info = elementary.Label(self.main.win)
	info.scale_set(3)
	info.size_hint_weight_set(1.0, 1.0)
	#info.color_set(0,255,0,255)
	#info.callback_add(self.ttt)
	#info.callback_add('kkk',self.ttt)
	info.size_hint_align_set(0.5, -1.0)
	info.label_set("")
	subbox.pack_end(info)
	info.show()
	#box.pack_end(scroller)
	
	global b
	
	b=elementary.Button(self.main.win)
	subbox.pack_end(b)
	
	#b.show()
	b.callback_clicked_add(self.ttt)
	icon = elementary.Icon(self.main.win)
	#b.label_set("N")
	#b.color_set(0, 0, 0, 255)
	icon.scale_set(4,4)
	icon.file_set(DATA_DIR + "images/preferences.png")
	b.icon_set(icon)
	icon.show()

	
        self.main.pager.content_push(self.box)
	bus.add_signal_receiver(self.courseUpdate, dbus_interface="org.freedesktop.Gypsy.Course", signal_name="CourseChanged")
	bus.add_signal_receiver(self.positionUpdate, dbus_interface="org.freedesktop.Gypsy.Position", signal_name="PositionChanged")
	bus.add_signal_receiver(self.GprsUpdate, dbus_interface="org.freesmartphone.GSM.PDP", signal_name="ContextStatus")
	bus.add_signal_receiver(self.GsmCallUpdate, dbus_interface="org.freesmartphone.GSM.Call", signal_name="CallStatus")
	
	try:
	    self.GprsUpdate()
	except:
            print "no gprs provider"

    def ttt(self, *xargs):
	  #self.main.test_toolbar(self)
	  self.main.notify_show("No last location :(", 2)

    def promote(self):
	#if not self.is_built:
	#    self.build()
	self.main.pager.content_promote(self.box)

    def togglegChanged(self, *args, **kargs):
        """establigh gprs"""
	
	#print toggleg.state_get()

	if toggleg.state_get():
	    #resources.gprs_obj.SetCredentials("internet", "internet", "internet")
	    resources.gprs_obj.ActivateContext(reply_handler = self.dbusnothing, error_handler = self.dbuserror)
	    #os.system("/home/root/net-on.sh")
	    toggleg.state_set(True)
            
	else:
	    resources.gprs_obj.DeactivateContext(reply_handler = self.dbusnothing, error_handler = self.dbuserror)
            toggleg.state_set(False)

    def toggleChanged(self, *args, **kargs):
        """Unlocks Screen if toggle is slided"""
	
	#print self.toggle.state_get()

	if self.toggle.state_get():
            #print "something moved"    
	    global action
            if action == "run":
		global force_send
		force_send=1
		self.main.aprs.send_now()
                #pass
            else:
		self.status_write ("Tracking START")
                action = "run"
                self.toggle.state_set(True)
                self.main.aprs.track_status()
                self.main.aprs.track()
            
	else:
	    self.status_write ("Tracking STOP")
	    action="stopit"
            self.toggle.state_set(False)

    def toggle_conChanged(self, *args, **kargs):
        """connects to aprs server"""

	if self.toggle_con.state_get():
	    self.toggle_con.state_set(True)
	    global connect_retry
	    connect_retry=10
	    self.main.aprs.connect_aprs()
	    self.main.aprs.track_maintenance()
	else:
            self.toggle_con.state_set(False)
	    self.main.aprs.disconnect_aprs()


    def status_write(self, text):
            global statusbuffer
	    statusbuffer.insert(0,text[:30])
            if (len(statusbuffer) > 3): #maxlines
                del(statusbuffer)[3]
                #print "deleting from list"
            write="<br>".join(statusbuffer)
            bt.entry_set(write.replace('\n', '<br>'))

    def positionUpdate(self, fso_fields=None, fso_tstamp=None, fso_lat=None, fso_lon=None, fso_alt=None, *args, **kargs):
        global POSITION, OLD_POSITION
        #print POSITION
	POSITION=[fso_fields, fso_tstamp,fso_lat, fso_lon,fso_alt]
	if POSITION[0]>=3: # if fix
	    OLD_POSITION=POSITION

    def courseUpdate(self, fso_fields=None, fso_tstamp=None, fso_speed=None, fso_course=None, fso_climb=None, *args, **kargs):
        global COURSE
        COURSE=[fso_fields, fso_tstamp,fso_speed, fso_course,fso_climb]
	
	global heading_old
	global delay_user
	#print "courseUpdate"
	speed=fso_speed *1.852
	inf= '<b>' + str(round(speed,1)) + '</b>'
	info.label_set(inf)
	
	heading_new=fso_course
	if (speed < 4):
	    delay_user = 120
	elif (11 > speed > 4):
	    delay_user = 80 #120
	elif (24 > speed > 11):
	    delay_user = 70 #2x60
	elif (40 > speed > 24):
	    delay_user = 60
	elif (60 > speed > 40):
	    delay_user = 50
	elif (90 > speed > 60):
	    delay_user = 40
	elif (130 > speed > 90):
	    delay_user = 30
	elif (speed > 130):
	    delay_user = 20 # 10
        self.toggle.states_labels_set("T: " + str(delay_user) + "s", "Not tracking")
	#print heading_old, heading_new

	if heading_old < heading_new:
		lesser = heading_old
		greater = heading_new
	else:
		lesser = heading_new
		greater = heading_old
	#print "delay minimum, speed: ", delay_minimum, speed
	#self.status_write('%s' % delay_minimum)
	difference = greater - lesser
	#ted=time.strftime('%H%M%S',time.localtime(time.time()))
	ted=time.time()
	rozdil=int(ted)-int(now_old)
	if action=="run":
	    status_bar.label_set("%s %s %s %s %s" % (rozdil,delay_user-rozdil, time.strftime('%H:%M:%S',time.localtime(now_old)), delay_user, action))	

	#print "course changed by ",  difference
	pac=str(self.main.aprs.get_position())
	#print "course update"
	#print pac
	if pac <> "wait":
	    if pac <> "nofix":
	        #print pac
	    	#print pac
	    	loc_e.entry_set("%s %s" %(time.strftime("%H:%M", time.localtime()),self.main.aprs.get_position('locator')))
	    	global __loc_last_location__
	    	__loc_last_location__ = pac
	    	#print "loc updated to", pac
		
    	
    	
	if (bearing_change < difference < (360-bearing_change)) and (action == "run") and (speed > 6):
	    self.main.main_page.status_write ("Course %s" % difference) 
	    self.main.aprs.send_now()


    def GprsUpdate(self, id = None, gprs_status = None, *args, **kargs):
    	#print "signal from GPRS"
	gprsstatus="UNKNOWN"
        if id == None:
	    #print "no ID..."
            resources.gprs_obj.GetContextStatus(reply_handler = self.GprsUpdate, error_handler=self.dbuserror)
        else:
            if gprs_status == None or gprs_status == {}:
                gprs_status = id.lower()
		gprsstatus="UNKNOWN"
            if gprs_status == 'release' or gprs_status == 'released':
                gprsstatus="disconnected"
		toggleg.state_set(False)
                
            elif gprs_status == 'active':
                gprsstatus="connected"
		toggleg.state_set(True)
                                
            elif gprs_status == 'outgoing':
                gprsstatus="connecting"
		toggleg.state_set(True)
                                
            elif gprs_status == 'incoming':
                gprsstatus="incoming"
		toggleg.state_set(True)
                
            elif gprs_status == 'held':
                gprsstatus="held"
		toggleg.state_set(True)
                
            else:
                gprsstatus="UNKNOWN"
                
	toggleg.states_labels_set(str(gprsstatus) , str(gprsstatus))	
	self.status_write("GPRS: "+str(gprsstatus))

    def GsmCallUpdate(self, id = None, gsm_status = None, *args, **kargs):
    	#print "signal from GPRS"
	#gsmstatus="UNKNOWN"
        #if id == None:
	#print "no ID..."
	#print "track toggle"
	#print self.main.main_page.toggle.state_get()
	global action
	
        if (gsm_status == "OUTGOING") or (gsm_status == "ACTIVE") or (gsm_status == "INCOMING"):
    	    if action == "run":
    		action = "stopit"
    		#self.toggle.state_set(False)
    		self.status_write("GSM: "+str(gsm_status) + " pause tracking")
    	elif gsm_status == "RELEASE":
    	    if self.main.main_page.toggle.state_get():
    	        #print "releasing tracking"
    		action = "run"
    		self.status_write("GSM: "+str(gsm_status) + " resume tracking")
    		#self.toggle.state_set(True)
    		self.main.aprs.track_status()
    		self.main.aprs.track()
    		#self.main.aprs.send_now()    		
    	
        #resources.gsm_obj.Call.CallStatus(reply_handler = self.GprsUpdate, error_handler=self.dbuserror)
	#print "GSM stats: " + gsm_status
	#toggleg.states_labels_set(str(gprsstatus) , str(gprsstatus))	
	self.status_write("GSM: "+str(gsm_status))

    
    def dbusnothing(self, *args, **kargs):
	print "gprs nothing"

    def dbuserror(self, *args, **kargs):
	print "gprs error"


class PreferencesPage(object):
    def __init__(self, main):
        self.main = main
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

        sc = elementary.Scroller(self.main.win)
        sc.bounce_set(False, True)
        sc.size_hint_weight_set(1.0, 1.0)
        sc.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(sc)
        sc.show()

        box = elementary.Box(self.main.win)
        box.size_hint_weight_set(1.0, 0)
        box.size_hint_align_set(-1, 0)
        sc.content_set(box)
        box.show()

	self.tg_fullscreen = elementary.Toggle(self.main.win)
	self.tg_fullscreen.icon_set(Icon(self.main.win, 'fullscreen.png'))
	self.tg_fullscreen.label_set("Full")
	self.tg_fullscreen.scale_set(1.5)
	self.tg_fullscreen.size_hint_weight_set(1, 0)
	self.tg_fullscreen.size_hint_align_set(-1, 0)
	self.tg_fullscreen.state_set(config.getboolean("general","fullscreen"))
	self.tg_fullscreen.states_labels_set("Yes", "No")
	#self.tg_fullscreen.callback_changed_add(self.toggle_fullscreen)
	self.tg_fullscreen.callback_changed_add(self.check_changed, "fullscreen", "fullscreen", "general")
	box.pack_end(self.tg_fullscreen)
	self.tg_fullscreen.show()

	self.tg_rotate = elementary.Toggle(self.main.win)
	self.tg_rotate.icon_set(Icon(self.main.win, 'view-refresh.png'))
	self.tg_rotate.label_set("Rot")
	self.tg_rotate.scale_set(1.5)
	self.tg_rotate.size_hint_weight_set(1, 0)
	self.tg_rotate.size_hint_align_set(-1, 0)
	self.tg_rotate.state_set(config.getboolean("general","rotation"))
	self.tg_rotate.states_labels_set("Yes", "No")
	self.tg_rotate.callback_changed_add(self.check_changed, "rotation", "rotation", "general")
	box.pack_end(self.tg_rotate)
	self.tg_rotate.show()


        toggled = elementary.Toggle(self.main.win)
        toggled.icon_set(Icon(self.main.win, 'dialog-information.png'))
        toggled.label_set("Dim")
        toggled.states_labels_set("No" , "Yes")
        toggled.state_set(config.getboolean("general","display"))
        toggled.scale_set(1.5)
	toggled.size_hint_weight_set(1, 0)
	toggled.size_hint_align_set(-1, 0) 
        toggled.callback_changed_add(self.check_changed, "display", "display", "general")
        box.pack_end(toggled)
        toggled.show()
        
        togglecpu = elementary.Toggle(self.main.win)
        togglecpu.icon_set(Icon(self.main.win, 'dialog-information.png'))
        togglecpu.label_set("Susp")
        togglecpu.states_labels_set("No" , "Yes")
        togglecpu.scale_set(1.5)
	togglecpu.size_hint_weight_set(1, 0)
	togglecpu.size_hint_align_set(-1, 0) 
        togglecpu.callback_changed_add(self.check_changed, "cpu", "cpu", "general")
        togglecpu.state_set(config.getboolean("general","cpu"))        
        box.pack_end(togglecpu)
        togglecpu.show()


        toggledisplay = elementary.Toggle(self.main.win)
        toggledisplay.icon_set(Icon(self.main.win, 'dialog-information.png'))
        toggledisplay.label_set("Mode")
        toggledisplay.states_labels_set("Night" , "Day")
        toggledisplay.scale_set(1.5)
	toggledisplay.size_hint_weight_set(1, 0)
	toggledisplay.size_hint_align_set(-1, 0) 
	toggledisplay.state_set(config.getboolean("general","lightmode")) 
	toggledisplay.callback_changed_add(self.check_changed, "lightmode", "lightmode", "general")
        box.pack_end(toggledisplay)
        toggledisplay.show()
        
	self.main.pager.content_push(self.box)

        boxcomment = elementary.Box(self.main.win)
        boxcomment.size_hint_weight_set(1.0, 0)
        boxcomment.horizontal_set(False)
        boxcomment.homogenous_set(True)
	boxcomment.size_hint_align_set(-1, -1)
        boxcomment.show()
        box.pack_end(boxcomment)

        aprs_check = elementary.Check(self.main.win)
        aprs_check.icon_set(Icon(self.main.win, 'atrack.png'))
        aprs_check.label_set('Aprs tracking')
        aprs_check.state_set(config.getboolean("aprs","enable"))
	aprs_check.size_hint_weight_set(1.0, 0)
	aprs_check.size_hint_align_set(-1.0, -1.0)
        aprs_check.callback_changed_add(self.check_changed, "aprs_enable", "enable", "aprs")
	aprs_check.show()

 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Comment</b><br>with packets (%s)<br>" % comment)
	comment_l.size_hint_weight_set(1, 1)
	comment_l.editable_set(False)
	#comment_l.callback_clicked_add(self.edit_entry, 'Edit Comment', comment, 'comment', 'aprs')
	comment_l._callback_add("clicked",self.edit_entry, 'Edit Comment', comment, 'comment', 'aprs')
	comment_l.size_hint_align_set(-1, -1)
	comment_l.show()

	boxcomment.pack_end(aprs_check)

	boxcomment.pack_end(comment_l)
	

        boxlogin = elementary.Box(self.main.win)
        boxlogin.size_hint_weight_set(1.0, 0)
        boxlogin.horizontal_set(True)
        boxlogin.homogenous_set(True)
	boxlogin.size_hint_align_set(-1, -1)
        boxlogin.show()

 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Username</b><br>Your HAM callsign (%s)<br>" % username)
	comment_l.size_hint_weight_set(1, 1)
	comment_l.size_hint_align_set(-1, -1)
	comment_l._callback_add("clicked", self.edit_entry, 'Edit Username', username, 'username', 'aprs')
#	comment_l._callback_add("clicked,double", self.edit_entry, 'Edit Username', username, 'username', 'aprs')

	comment_l.editable_set(False)
	comment_l.show()
        
	
	boxlogin.pack_end(comment_l)

        boxpassword = elementary.Box(self.main.win)
        boxpassword.size_hint_weight_set(1.0, 0)
        boxpassword.horizontal_set(True)
        boxpassword.homogenous_set(True)
	boxpassword.size_hint_align_set(-1, -1)
        boxpassword.show()

 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Password</b><br>aprs password (******)<br>")
	comment_l.size_hint_weight_set(1, 1)
	comment_l.size_hint_align_set(-1, -1)
	comment_l._callback_add("clicked",self.edit_entry, 'Edit Password', password, 'password', 'aprs')
	comment_l.editable_set(False)
	comment_l.show()
	
	boxpassword.pack_end(comment_l)

        boxfilter = elementary.Box(self.main.win)
        boxfilter.size_hint_weight_set(1.0, 0)
        boxfilter.horizontal_set(True)
        boxfilter.homogenous_set(True)
	boxfilter.size_hint_align_set(-1, -1)
        boxfilter.show()

 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Filter</b><br>m/distance b/buddy (%s)<br>" % aprsfilter)
	comment_l.size_hint_weight_set(1, 1)
	comment_l.size_hint_align_set(-1, -1)
	comment_l._callback_add("clicked",self.edit_entry, 'Edit Filter', aprsfilter, 'filter', 'aprs')
	comment_l.editable_set(False)
	comment_l.show()

	boxfilter.pack_end(comment_l)

        boxtimeout = elementary.Box(self.main.win)
        boxtimeout.size_hint_weight_set(1.0, 0)
        boxtimeout.horizontal_set(True)
        boxtimeout.homogenous_set(True)
	boxtimeout.size_hint_align_set(-1, -1)
        boxtimeout.show()

 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Timeout to hide dead stations</b><br>time in minutes (%s)<br>" % timeout)
	comment_l.size_hint_weight_set(1, 1)
	comment_l.size_hint_align_set(-1, -1)
	comment_l._callback_add("clicked",self.edit_entry, 'Edit Timeout', timeout, 'timeout', 'aprs')
	comment_l.editable_set(False)
	comment_l.show()

	boxtimeout.pack_end(comment_l)


        boxstatus = elementary.Box(self.main.win)
        boxstatus.size_hint_weight_set(1.0, 0)
        boxstatus.horizontal_set(True)
        boxstatus.homogenous_set(True)
	boxstatus.size_hint_align_set(-1, -1)
        boxstatus.show()
        
	
 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Status</b><br>autosending (%s)<br>" % aprsstatus)
	comment_l.size_hint_weight_set(1, 1)
	comment_l.size_hint_align_set(-1, -1)
	comment_l._callback_add("clicked",self.edit_entry, 'Edit Status', aprsstatus, 'aprsstatus', 'aprs')
	comment_l.editable_set(False)
	comment_l.show()


	boxstatus.pack_end(comment_l)


        boxyouloc = elementary.Box(self.main.win)
        boxyouloc.size_hint_weight_set(1.0, 0)
        boxyouloc.horizontal_set(False)
        boxyouloc.homogenous_set(True)
	boxyouloc.size_hint_align_set(-1, -1)
        boxyouloc.show()
        
        
        youloc_check = elementary.Check(self.main.win)
        youloc_check.label_set("Youloc tracking")
        youloc_check.icon_set(Icon(self.main.win, 'youloc.png'))
        youloc_check.state_set(config.getboolean("youloc","enable"))
	youloc_check.size_hint_weight_set(1.0, 0)
	youloc_check.size_hint_align_set(-1.0, -1.0)
        #aprs_toggle.scale_set(1.5)
        youloc_check.callback_changed_add(self.check_changed, "youloc_enable", "enable", "youloc")
	youloc_check.show()

        
 	comment_l=elementary.Entry(self.main.win)
	comment_l.entry_set("<b>Key</b><br>Youloc device key (%s)<br>" %__youloc_userkey__)
	comment_l.size_hint_weight_set(1, 1)
	comment_l.size_hint_align_set(-1, -1)
	comment_l._callback_add("clicked",self.edit_entry, 'Edit Key',__youloc_userkey__, 'userkey', 'youloc')
	comment_l.editable_set(False)
	comment_l.show()


	boxyouloc.pack_end(youloc_check)

	boxyouloc.pack_end(comment_l)


        boxlabel = elementary.Box(self.main.win)
        boxlabel.size_hint_weight_set(1.0, 0)
        boxlabel.horizontal_set(True)
        boxlabel.homogenous_set(True)
	boxlabel.size_hint_align_set(-1, -1)
        boxlabel.show()

 	comment_l=elementary.Label(self.main.win)
	comment_l.label_set("<b>APRS</b><br>Reconnecting required!")
	#comment_l.size_hint_weight_set(0, 1)
	#comment_l.size_hint_align_set(0, 1)
	comment_l.show()
	boxlabel.pack_end(comment_l)
	
        boxlabel2 = elementary.Box(self.main.win)
        boxlabel2.size_hint_weight_set(1.0, 0)
        boxlabel2.horizontal_set(True)
        boxlabel2.homogenous_set(True)
	boxlabel2.size_hint_align_set(-1, -1)
        boxlabel2.show()
	youloc_l=elementary.Label(self.main.win)
	youloc_l.label_set("<b>Youloc</b>")
	#comment_l.size_hint_weight_set(0, 1)
	#comment_l.size_hint_align_set(0, 1)
	youloc_l.show()
	boxlabel2.pack_end(youloc_l)

	box.pack_end(boxlabel)
	box.pack_end(boxcomment)
	box.pack_end(boxstatus)
	
        box.pack_end(boxlogin)
        box.pack_end(boxpassword)
        box.pack_end(boxfilter)
        box.pack_end(boxtimeout)
        

	box.pack_end(boxlabel2)
        box.pack_end(boxyouloc)
	
        

	#packet + send button
        box3 = elementary.Box(self.main.win)
        box3.size_hint_weight_set(1.0, 0)
        box3.horizontal_set(True)
        box3.homogenous_set(True)
	box3.size_hint_align_set(-1, -1)
        box3.show()
        
        
       	#locator_l=elementary.Label(self.main.win)
	#locator_l.label_set("<b>Locator:</b>")
	##status_l.size_hint_weight_set(0, 1)
	#locator_l.size_hint_align_set(0, 1)
	#locator_l.show()  
	
	loc_button = elementary.Button(self.main.win)
	loc_button.label_set("Send Last loc")
	loc_button.callback_clicked_add(self.send_loc)
	loc_button.show()
	loc_button.size_hint_weight_set(1.0, 0.0)
	loc_button.size_hint_align_set(-1, 0)
	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/mail-reply-sender.png")
	loc_button.icon_set(icon)
	icon.show()

	global loc_e
	
	loc_e = elementary.Entry(self.main.win)                      
	loc_e.entry_set("No fix")
	loc_e.editable_set(False)
	loc_e.single_line_set(True)
	loc_e.scale_set(1)
	loc_e.size_hint_weight_set(1, 1)
	loc_e.size_hint_align_set(-1, -1)
	
	#box3.pack_end(locator_l)
	box3.pack_end(loc_e)
	box3.pack_end(loc_button)
	loc_e.show()                          
	box.pack_end(box3)
	global __loc_last_location__


    def check_changed(self, check,preference, value, group, *args):
    	global __youloc_enable__, __aprs_enable__
    	item = check.state_get()
    	if preference == 'youloc_enable':
	    __youloc_enable__ = item
        elif preference == 'aprs_enable':
            __aprs_enable__ = item
        elif preference=='rotation':
            self.main.win.rotation_set(item * 90)
        elif preference =='fullscreen':
            self.main.win.fullscreen_set(item)
        elif preference == 'cpu':
    	    if item:
    	    	try:   
    	           resources.usage_iface.RequestResource("CPU")
    	        except:
    	           pass
            else:
            	try:
	            resources.usage_iface.ReleaseResource("CPU")
	        except:
	            pass
        elif preference == 'display':
    	    if item:
    	    	try:
    	            resources.usage_iface.RequestResource("Display")
    	        except:
    	            pass
            else:
            	try:
	            resources.usage_iface.ReleaseResource("Display") 
	        except:
	            pass
        elif preference =='lightmode':
            if item:
            	try:	
            	    resources.phonefso_iface.SetDefaultBrightness(30)
                except:
                    print "error in brightnes"
            else:
            	try:
                    resources.phonefso_iface.SetDefaultBrightness(80)
                except:
                    print "error in brightnes"
        	
        else:
            print "error in check preference name"
            
    	config.set(group,value,item)
    	save_config()
    
    def edit_entry(self, entry, title, value, preference, group, *xargs):
    	#print self
    	#print entry
    	#print group, preference, value, "\n"
    	#print preference
    	#print group
    	#sys.exit()

    	def ok_save(self, preference):
    	    if loc_e.entry_get()<>'':
    	    	item=str(loc_e.markup_to_utf8(loc_e.entry_get()).replace('\n',''))
            else:
            	item=''
            set_win.hide()

	    global config
	    global username, comment, password, aprsstatus,path, timeout
	    global delay_user, serverhost, serverport, aprsfilter
	    global home_qth, aprs_symbol, aprs_table_overlay, serverPort, serverHost
	    global __youloc_enable__, __youloc_userkey__,__aprs_enable__
	    global TEMPLATE_LIST, CALLER_LIST
	    
	    if preference == 'username':
	    	username = item
	    elif preference == 'comment':
	    	comment = item
	    elif preference == 'password':
	        password=item 
	    elif preference == 'aprsstatus':
	        aprsstatus=item
	    elif preference == 'serverhost':
	    	serverhost = item
	    elif preference == 'serverport':
	    	serverport = item
	    elif preference == 'filter':
	    	aprsfilter = item
	    elif preference == 'timeout':
	    	timeout = item
	    elif preference == 'userkey':
	    	__youloc_userkey__ = item
	    else:
	    	print 'error in preference name'

	    path = "%s>%s:" % (username,aprs_path)
	    #self.main.main_page.toggle.state_set(False)
	    #self.main.main_page.toggle_con.state_set(False)
	    	
	    #print group, preference, item
	    config.set(group, preference, item)
	    save_config()
	    	    	
    	def ca_cancel(self):
    	    set_win.hide()
    	    
    	set_win = elementary.Window('title', elementary.ELM_WIN_DIALOG_BASIC)
    	set_win.callback_destroy_add(ca_cancel)
    	set_win.title_set('%s' % title)
    	
	bgg = elementary.Background(set_win)
        set_win.resize_object_add(bgg)
        #bgg.file_set("/home/root/atrack.png")
        bgg.size_hint_weight_set(1.0, 1.0)
        bgg.show()

	box = elementary.Box(set_win)
    	box.show()
    	
        set_win.resize_object_add(box)

        but_box = elementary.Box(set_win)
        but_box.size_hint_weight_set(1.0, 0)
        but_box.horizontal_set(True)
        but_box.homogenous_set(True)
	but_box.size_hint_align_set(-1, -1)
        but_box.show()
        
        ent_box = elementary.Box(set_win)
        ent_box.size_hint_weight_set(1.0, 0)
        #ent_box.horizontal_set(True)
        ent_box.homogenous_set(True)
	ent_box.size_hint_align_set(-1, -1)
        ent_box.show()
        
        box.pack_end(ent_box)
        box.pack_end(but_box)

 	comment_l=elementary.Label(set_win)
 	label=entry.entry_get()
	comment_l.label_set(label)
	#comment_l.size_hint_weight_set(0, 1)
	#comment_l.size_hint_align_set(0, 1)
	comment_l.show()
	ent_box.pack_end(comment_l)


	loc_e = elementary.Entry(set_win)                    
	loc_e.entry_set(config.get(group,preference))
	#loc_e.editable(False)
	loc_e.single_line_set(True)
	loc_e.scale_set(1)
	loc_e.size_hint_weight_set(1, 1)
	loc_e.size_hint_align_set(-1, -1)
	loc_e.show()

	ent_box.pack_end(loc_e)
	ok_button = elementary.Button(set_win)
	ok_button.label_set("OK")
	ok_button.callback_clicked_add(ok_save, preference)
	ok_button.show()
	ok_button.size_hint_weight_set(1.0, 0.0)
	ok_button.size_hint_align_set(-1, 0)
	icon = elementary.Icon(set_win)
	icon.file_set(DATA_DIR + "/images/mail-reply-sender.png")
	ok_button.icon_set(icon)
	icon.show()    
    
	ca_button = elementary.Button(set_win)
	ca_button.label_set("Cancel")
	ca_button.callback_clicked_add(ca_cancel)
	ca_button.show()
	ca_button.size_hint_weight_set(1.0, 0.0)
	ca_button.size_hint_align_set(-1, 0)
	icon = elementary.Icon(set_win)
	icon.file_set(DATA_DIR+ "images/mail-reply-sender.png")
	ca_button.icon_set(icon)
	icon.show()    

	but_box.pack_end(ok_button)
	but_box.pack_end(ca_button)
	set_win.show()
      
      
    def send_status(self, *args, **kargs):
    	
        if __aprs_enable__:
		if aprsstatus <> "":
			try:
			    #self.main.main_page.status_write ("Status %s %s" % (username, aprsstatus))
			    #TODO: do some basic comment striping here
			    self.main.aprs.send_data(">%s" % aprsstatus) #send status message
			    
			except:
			    status = "NO NETWORK"
			    self.main.main_page.status_write(status)
			    self.reconnect()

    def send_loc(self, *args, **kargs):
    	#print "loc: ",__loc_last_location__
    	if (__loc_last_location__ != "") :
		try:
		    self.main.main_page.status_write ("Position<br>%s" % __loc_last_location__)
		    #TODO: do some basic comment striping here
		    self.main.aprs.sock.sendall("%s" % __loc_last_location__) #send status message
		    
		except:
		    status = "NO NETWORK"
		    self.main.main_page.status_write(status)
		    self.reconnect()
        else:	
        	self.main.main_page.status_write ("No location")
        	self.main.notify_show("No last location :(", 2)


class MessagesPage(object):
    def __init__(self, main):
        self.main = main

        # main box
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

#        label = elementary.Label(self.main.win)
#        label.label_set('<b>%s %s</>' % (appname, appversion))
#        label.size_hint_weight_set(0, 0)
#        label.size_hint_align_set(0.5, 0.5)
#        self.box.pack_end(label)
#        label.show()

        scroller = elementary.Scroller(self.main.win)
        scroller.bounce_set(False, True)
        scroller.size_hint_weight_set(1.0, 1.0)
        scroller.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(scroller)
        scroller.show()

        self.box2 = elementary.Box(self.main.win)
        self.box2.size_hint_weight_set(1, 1)
        self.box2.size_hint_align_set(-1, -1)
        scroller.content_set(self.box2)
        self.box2.show()

	self.render_message("Foo", "Today", "Bar", "This is a demo message and it is pretty long to make sure we can test wrapping. And yes, it also has some long lines, for example this one continues here...")


        self.main.pager.content_push(self.box)

    def create_message(self, button, callsign):
	  self.main.create_message_page.prepare_message(self, callsign)
          
    def forward_message(self, button, callsign, text):
	  self.main.create_message_page.prepare_message(self, callsign, text)


    def render_message(self, callsign, timestamp, recepient, msgtext, *args, **kargs):
    	  bubble = elementary.Bubble(self.main.win)

	  textbox = elementary.Box(self.main.win)
	  text = elementary.AnchorBlock(self.main.win)
	  textbox.pack_start(text)

	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/internet-mail.png")
	  bubble.icon_set(icon)
	  icon.show()
	  bubble.info_set(timestamp)
	  if (recepient==username):
	  	  bubble.label_set(callsign + ">me")
	  elif (callsign==username):
	  	  bubble.label_set("me>" + recepient)
	  else: 
	  	  bubble.label_set("Oth: "+callsign + ">" + recepient)
	  	  
	  bubble.size_hint_weight_set(-1.0, 0.0)
	  bubble.size_hint_align_set(-1.0, -1.0)

	  content = "\n" + msgtext
	  if not content:
	    content = ''
	  content = elementary.Entry.utf8_to_markup(content)
	  if not content:
	    content = ''
	  text.text_set(content)

	  bubble.content_set(textbox)
	  text.show()

	  self.box2.pack_start(bubble)
	  bubble.show()


	  btnframe = elementary.Frame(self.main.win)
	  btnframe.style_set("outdent_bottom")
	  btnframe.size_hint_weight_set(1.0, 0.0)
	  btnframe.size_hint_align_set(-1.0, -1.0)
	  btnframe.show()
	  
	  def delete_msg(self,bubble):
	      pass
    	      bubble.delete()
	      del bubble

	  

	      	      
	      	      
	  deletebutton = elementary.Button(self.main.win)
	  deletebutton.label_set("Delete")
	  deletebutton.callback_clicked_add(delete_msg,bubble)
	  deletebutton.show()
	  deletebutton.size_hint_weight_set(1.0, 0.0)
	  deletebutton.size_hint_align_set(1.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/mail-mark-junk.png")
	  deletebutton.icon_set(icon)
	  icon.show()

	  hbox = elementary.Box(self.main.win)
	  hbox.horizontal_set(1)
	  hbox.show()

	  replybutton = elementary.Button(self.main.win)
	  replybutton.label_set("Reply")
	  replybutton.callback_clicked_add(self.create_message, callsign)
	  replybutton.show()
	  replybutton.size_hint_weight_set(0.0, 0.0)
	  replybutton.size_hint_align_set(0.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/mail-reply-sender.png")
	  replybutton.icon_set(icon)
	  icon.show()
	  
	  
	  forwbutton = elementary.Button(self.main.win)
	  forwbutton.label_set("Forward")
	  forwbutton.callback_clicked_add(self.forward_message, callsign, msgtext)
	  forwbutton.show()
	  forwbutton.size_hint_weight_set(0.0, 0.0)
	  forwbutton.size_hint_align_set(0.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/mail-forward.png")
	  forwbutton.icon_set(icon)
	  icon.show()
	  
	  hbox.pack_start(replybutton)
	  hbox.pack_end(forwbutton)

	  hbox.pack_end(deletebutton)
	  btnframe.content_set(hbox)

	  textbox.size_hint_weight_set(-1.0, 0.0)
	  textbox.size_hint_align_set(-1.0, -1.0)
	  text.size_hint_weight_set(-1.0, 0.0)
	  text.size_hint_align_set(-1.0, -1.0)

	  textbox.pack_end(btnframe)
	  textbox.show()
	  
	  

class CreateMessagePage(object):
    def __init__(self, main, callsign='', text=''):
        self.main = main

        # main box
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

        scroller = elementary.Scroller(self.main.win)
        scroller.bounce_set(False, True)
        scroller.size_hint_weight_set(1.0, 1.0)
        scroller.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(scroller)
        scroller.show()

        box = elementary.Box(self.main.win)
        box.size_hint_weight_set(1, 1)
        box.size_hint_align_set(-1, -1)
	#box.homogenous_set(True)
        scroller.content_set(box)
        box.show()

        csbox = elementary.Box(self.main.win)
        csbox.size_hint_weight_set(1, 0)
        csbox.size_hint_align_set(-1, 0)
	csbox.homogenous_set(True)
	csbox.horizontal_set(True)
	box.pack_start(csbox)
        csbox.show()


        alabel_callsign = elementary.Label(self.main.win)
        alabel_callsign.size_hint_weight_set(0, 0)
        alabel_callsign.size_hint_align_set(0, 0)
        alabel_callsign.label_set('Callsign:')
	#box.pack_start(alabel_callsign)        
	csbox.pack_end(alabel_callsign)
        alabel_callsign.show()	        
        
        
        global label_callsign
        if not callsign: callsign  = ''
        label_callsign = elementary.Entry(self.main.win)
        label_callsign.editable_set(True)
        #label_callsign.line_wrap_set(True)
        label_callsign.single_line_set(True)
        label_callsign.size_hint_weight_set(1, 0)
        label_callsign.size_hint_align_set(-1, 0)
        
        label_callsign.entry_set(callsign)
	#box.pack_end(label_callsign)
	csbox.pack_end(label_callsign)        
        label_callsign.show()


        
	blabel_callsign = elementary.Label(self.main.win)
        blabel_callsign.size_hint_weight_set(-1, -1)
        blabel_callsign.size_hint_align_set(-1, -1)
        blabel_callsign.label_set('Message text:')
        box.pack_end(blabel_callsign)
        blabel_callsign.show()        
        
	global label_text
	if not text:  text = ''
        label_text = elementary.Entry(self.main.win)
        label_text.editable_set(True)
        label_text.color_set(255, 255, 255, 255)
        #label_text.single_line_set(True)
        label_text.line_wrap_set(True)
        label_text.size_hint_weight_set(1, 1)
        label_text.size_hint_align_set(-1, -1)
        label_text.entry_set(text)
        box.pack_end(label_text)
        label_text.show()

	btnframe = elementary.Frame(self.main.win)
	btnframe.style_set("outdent_bottom")
	btnframe.size_hint_weight_set(1.0, 0.0)
	btnframe.size_hint_align_set(-1.0, -1.0)
	btnframe.show()


	hbox = elementary.Box(self.main.win)
	hbox.horizontal_set(1)
	hbox.show()
	
	def change_template(self, item = None, mode = None):
	    if (TEMPLATE_LIST[mode]['name']=="clear"):
	        label_text.entry_set('')
	    else:
	        label_text.entry_insert('%s' % TEMPLATE_LIST[mode]['text'])
 		
	def change_caller(self, item = None, mode = None):
	    label_callsign.entry_set('%s' % CALLER_LIST[mode]['text'])
	
	bt = elementary.Hoversel(self.main.win)
	bt.hover_parent_set(self.main.win)
	#bt.scale_set(1)
	bt.label_set("")
	
        for mode in TEMPLATE_LIST:
            bt.item_add(
                mode['name'],
                "arrow_right", elementary.ELM_ICON_STANDARD,
                change_template, mode['id']
                )
 
	
	bt.size_hint_weight_set(1.0, 1.0)
	bt.size_hint_align_set(-1, -1)
	

	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/bookmark-new.png")
	bt.icon_set(icon)
	icon.show()
	
	bt.show()

	hs_call = elementary.Hoversel(self.main.win)
	hs_call.hover_parent_set(self.main.win)
	#hs_call.scale_set(1)
	hs_call.label_set("")
	
        for mode in CALLER_LIST:
            hs_call.item_add(
                mode['name'],
                "arrow_right", elementary.ELM_ICON_STANDARD,
                change_caller, mode['id']
                )
 
	
	hs_call.size_hint_weight_set(1.0, 1.0)
	hs_call.size_hint_align_set(-1, -1)
	#bx.pack_end(bt)
	

	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/address-book-new.png")
	hs_call.icon_set(icon)
	icon.show()
	
	hs_call.show()



	btn_r = elementary.Button(self.main.win)
	btn_r.label_set(' Send')
	btn_r.size_hint_weight_set(1, 1)
	btn_r.size_hint_align_set(-1, -1)
	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/mail-reply-all.png")
	btn_r.icon_set(icon)
	icon.show()
	btn_r.show()


	
	hbox.pack_start(hs_call)
	hbox.pack_end(bt)
	hbox.pack_end(btn_r)
	btnframe.content_set(hbox)

	box.pack_end(btnframe)
        def send(*args):
    	    if (str(label_callsign.entry_get())<>'') and str(label_text.entry_get()<>''):
        	self.main.aprs.send_message(str(label_callsign.entry_get()), str(label_text.entry_get()))
	
	btn_r._callback_add('clicked',send)

        self.main.pager.content_push(self.box)
                                                

    
    def prepare_message(self, button, callsign, text=''):
    	global VIEW_STATION
    	VIEW_STATION=''
    	label_callsign.entry_set(callsign)
    	label_text.entry_set(text)
    	#self.main.toolbar_item_create_message.select()
    	self.main.show_create_message_page()
    	
class CreateObjectPage(object):
    def __init__(self, main, callsign='', text=''):
        self.main = main

        # main box
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

        scroller = elementary.Scroller(self.main.win)
        scroller.bounce_set(False, True)
        scroller.size_hint_weight_set(1.0, 1.0)
        scroller.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(scroller)
        scroller.show()

        box = elementary.Box(self.main.win)
        box.size_hint_weight_set(1, 1)
        box.size_hint_align_set(-1, -1)
	#box.homogenous_set(True)
        scroller.content_set(box)
        box.show()

        csbox = elementary.Box(self.main.win)
        csbox.size_hint_weight_set(1, 0)
        csbox.size_hint_align_set(-1, 0)
	csbox.homogenous_set(True)
	csbox.horizontal_set(True)
	
        csbox.show()


        alabel_name = elementary.Label(self.main.win)
        alabel_name.size_hint_weight_set(0, 0)
        alabel_name.size_hint_align_set(0, 0)
        alabel_name.label_set('Name:')
	#box.pack_start(alabel_callsign)        
	csbox.pack_end(alabel_name)
        alabel_name.show()	        
        
        
        global entry_name
        #if not callsign: callsign  = ''
        entry_name = elementary.Entry(self.main.win)
        entry_name.editable_set(True)
        #label_callsign.line_wrap_set(True)
        entry_name.single_line_set(True)
        entry_name.size_hint_weight_set(1, 0)
        entry_name.size_hint_align_set(-1, 0)
        
        #entry_name.entry_set(callsign)
	#box.pack_end(label_callsign)
	csbox.pack_end(entry_name)        
        entry_name.show()

        commentbox = elementary.Box(self.main.win)
        commentbox.size_hint_weight_set(1, 0)
        commentbox.size_hint_align_set(-1, 0)
	commentbox.homogenous_set(True)
	commentbox.horizontal_set(True)
	
        commentbox.show()

        
	label_comment = elementary.Label(self.main.win)
        label_comment.size_hint_weight_set(-1, -1)
        label_comment.size_hint_align_set(-1, -1)
        label_comment.label_set('Comment:')
        commentbox.pack_end(label_comment)
        label_comment.show()        
        
	global entry_comment
	#if not text:  text = ''
        entry_comment = elementary.Entry(self.main.win)
        entry_comment.editable_set(True)
        entry_comment.color_set(255, 255, 255, 255)
        #label_text.single_line_set(True)
        entry_comment.line_wrap_set(True)
        entry_comment.size_hint_weight_set(1, 1)
        entry_comment.size_hint_align_set(-1, -1)
        #entry_comment.entry_set(text)
        commentbox.pack_end(entry_comment)
        entry_comment.show()


	locatorbox = elementary.Box(self.main.win)
        locatorbox.size_hint_weight_set(1, 0)
        locatorbox.size_hint_align_set(-1, 0)
	locatorbox.homogenous_set(True)
	locatorbox.horizontal_set(True)
        locatorbox.show()

	#label_locator = elementary.Label(self.main.win)
        #label_locator.size_hint_weight_set(-1, -1)
        #label_locator.size_hint_align_set(-1, -1)
        #label_locator.label_set('Position:')
	#locatorbox.pack_end(label_locator)        
        #label_locator.show()        

	locatorbox_lat, locatorbox_lon, locatorbox_course=self.main.aprs.get_position("distance")

	global entry_lon
	#if not text:  text = ''
        entry_lon = elementary.Entry(self.main.win)
        entry_lon.editable_set(True)
        entry_lon.color_set(255, 255, 255, 255)
        entry_lon.single_line_set(True)
        entry_lon.line_wrap_set(True)
        entry_lon.size_hint_weight_set(1, 1)
        entry_lon.size_hint_align_set(-1, -1)
        entry_lon.entry_set(str(locatorbox_lon))
        
        entry_lon.show()
        
        
	global entry_lat
	#if not text:  text = ''
        entry_lat = elementary.Entry(self.main.win)
        entry_lat.editable_set(True)
        entry_lat.color_set(255, 255, 255, 255)
        entry_lat.single_line_set(True)
        entry_lat.line_wrap_set(True)
        entry_lat.size_hint_weight_set(1, 1)
        entry_lat.size_hint_align_set(-1, -1)
        entry_lat.entry_set(str(locatorbox_lat))
        
        entry_lat.show()
        
        
        locatorbox.pack_end(entry_lat)
        locatorbox.pack_end(entry_lon)

	button_locator = elementary.Button(self.main.win)
	button_locator.label_set('GPS')
	button_locator.size_hint_weight_set(1, 1)
	button_locator.size_hint_align_set(-1, -1)
	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/mail-reply-all.png")
	button_locator.icon_set(icon)
	icon.show()
	button_locator.show()
	locatorbox.pack_end(button_locator)
	
	
	typebox = elementary.Box(self.main.win)
        typebox.size_hint_weight_set(1, 0)
        typebox.size_hint_align_set(-1, 0)
	typebox.homogenous_set(True)
	typebox.horizontal_set(True)
        typebox.show()
        
        global hs_type
	hs_type = elementary.Hoversel(self.main.win)
	hs_type.hover_parent_set(self.main.win)
	#hs_call.scale_set(1)
	hs_type.label_set("Select type")
	
	TYPE_LIST = (
    {
        'id':       0,
        'name':     'Item',
        'text':         'Item',             
        },
    {
        'id':       1,
        'name':     'Object',
        'text':         'Object',
        },
        
      {
        'id':       2,
        'name':     'Query',
        'text':         'Query',
        },  
        
      {
        'id':       3,
        'name':     'Message',
        'text':         'Message',
        },  
           
        
    )

	def go_to_message(*xargs):
	    #self.main.toolbar_item_create_message.select()
	    self.main.show_create_message_page()

	def change_type(self, item = None, mode = None):
		hs_type.label_set('%s' % TYPE_LIST[mode]['text'])
		
		if TYPE_LIST[mode]['name']=="Query":
			locatorbox.hide()
			#entry_comment.entry_set('?')
			alabel_name.label_set('Callsign:')
			label_comment.label_set('Query:')
			hs_call.hide()
			hs_query.show()
		elif TYPE_LIST[mode]['name']=="Message":
			hs_type.label_set("Select type")
			go_to_message()
			
		else:
			locatorbox.show()
			commentbox.show()
			hs_call.show()
			hs_query.hide()
			alabel_name.label_set('Name:')
			label_comment.label_set('Comment:')
			
		
		
	
        for mode in TYPE_LIST:
            hs_type.item_add(
                mode['name'],
                "arrow_right", elementary.ELM_ICON_STANDARD,
                change_type, mode['id']
                )
 
	
	hs_type.size_hint_weight_set(1.0, 1.0)
	hs_type.size_hint_align_set(-1, -1)
	typebox.pack_end(hs_type)
	hs_type.show()
	
	
	box.pack_end(typebox)
	
	
	box.pack_end(csbox)
	box.pack_end(commentbox)
	box.pack_end(locatorbox)
        
	
	btnframe = elementary.Frame(self.main.win)
	btnframe.style_set("outdent_bottom")
	btnframe.size_hint_weight_set(1.0, 0.0)
	btnframe.size_hint_align_set(-1.0, -1.0)
	btnframe.show()


	hbox = elementary.Box(self.main.win)
	hbox.horizontal_set(1)
	hbox.show()
	
	def change_caller(self, item = None, mode = None):
	    if (OBJECT_LIST[mode]['name']=="clear"):
	        entry_comment.entry_set('')
	        entry_name.entry_set('')
	    else:
		entry_name.entry_set('%s' % OBJECT_LIST[mode]['text'])
	
	
	

	hs_call = elementary.Hoversel(self.main.win)
	hs_call.hover_parent_set(self.main.win)
	hs_call.label_set("Names")
	
        for mode in OBJECT_LIST:
            hs_call.item_add(
                mode['name'],
                "arrow_right", elementary.ELM_ICON_STANDARD,
                change_caller, mode['id']
                )
 
	
	hs_call.size_hint_weight_set(1.0, 1.0)
	hs_call.size_hint_align_set(-1, -1)
	#bx.pack_end(bt)
	

	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/address-book-new.png")
	hs_call.icon_set(icon)
	icon.show()
	
	hs_call.show()

	QUERY_LIST = (
    {
        'id':       0,
        'name':     'Position',
        'text':         'P',
        },
        
      {
        'id':       1,
        'name':     'Status',
        'text':         'S',
        },  
        
      {
        'id':       2,
        'name':     'Stations Heard',
        'text':         'D',
        },  

      {
        'id':       3,
        'name':     'Heard Station',
        'text':         'H',
        },  
        
              {
        'id':       4,
        'name':     'Objects',
        'text':         'O',
        },  
        
        
              {
        'id':       5,
        'name':     'Messages',
        'text':         'M',
        },  
        
        
    )


	def change_query(self, item = None, mode = None):
		entry_comment.entry_set('%s' % QUERY_LIST[mode]['text'])
		

	hs_query = elementary.Hoversel(self.main.win)
	hs_query.hover_parent_set(self.main.win)
	hs_query.label_set("Direct query")
	
        for mode in QUERY_LIST:
            hs_query.item_add(
                mode['name'],
                "arrow_right",elementary.ELM_ICON_STANDARD ,
                change_query, mode['id']
                )
 
	
	hs_query.size_hint_weight_set(1.0, 1.0)
	hs_query.size_hint_align_set(-1, -1)
	#bx.pack_end(bt)
	

	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/address-book-new.png")
	hs_query.icon_set(icon)
	icon.show()
	hs_query.show()
	
	
	btn_r = elementary.Button(self.main.win)
	btn_r.label_set(' Send')
	btn_r.size_hint_weight_set(1, 1)
	btn_r.size_hint_align_set(-1, -1)
	icon = elementary.Icon(self.main.win)
	icon.file_set(DATA_DIR + "images/mail-reply-all.png")
	btn_r.icon_set(icon)
	icon.show()
	btn_r.show()


	
	hbox.pack_start(hs_call)
	hbox.pack_end(hs_query)
	
	sbox = elementary.Box(self.main.win)
        sbox.size_hint_weight_set(1, 0)
        sbox.size_hint_align_set(-1, 0)
        sbox.show()
	
	sbox.pack_end(btn_r)
	btnframe.content_set(hbox)
	box.pack_end(btnframe)
	box.pack_end(sbox)
	

	
	def update_pos(*args):
	    locatorbox_lat, locatorbox_lon, locatorbox_course=self.main.aprs.get_position("distance")
	    if POSITION[0]<3:
	    	self.main.notify_show("No fix, using last or home", 2)
            entry_lat.entry_set(str(locatorbox_lat))
            entry_lon.entry_set(str(locatorbox_lon))
        
       	button_locator.callback_clicked_add(update_pos)


        def send_object(*args):
            erra=""
            object_comment=''
            if hs_type.label_get() == "Select type": 
            	erra += "Type "
            if entry_name.entry_get() =="": 
            	erra += "Name "
            	
            if hs_type.label_get() == "Item" or hs_type.label_get() == "Object":
		    try:
			float(entry_lat.entry_get())
		    except:
			erra+="Latitude "
		    try:
			float(entry_lon.entry_get())
		    except:
			erra+="Longitude "
			
            if erra <> "":
            	    self.main.notify_show("Please fix these:<br>%s" % erra, 5)
            else:
                if hs_type.label_get() == "Item":
                    object_type=")"
                elif hs_type.label_get() == "Object": 
            	    object_type=";"
                elif hs_type.label_get()=="Query":
            	    object_type="query"
            	else:
            	    self.main.notify_show("Incorect item type %s" % hs_type.label_get(), 5)
            
            	if entry_comment.entry_get()<>"":
            	    object_comment=entry_comment.entry_get()
            
            	object_name=entry_name.entry_get()[:9]
                
                object_sym_tbl="/"
                object_sym_code="/"
                object_timestamp=""
                object_alive="!"
                
                if object_type==";" or object_type==")":
                
			if object_type==";":
			    object_timestamp=time.strftime('%H%M%Sh',time.gmtime(time.time()))
			    object_alive="*"
			    object_name=object_name.ljust(9)
			else:
			    object_name=object_name.ljust(3)
			
			compr_lat=self.main.aprs.compress_lat(float(entry_lat.entry_get()))
			compr_lon=self.main.aprs.compress_lon(float(entry_lon.entry_get()))
			
			poslat=''.join(compr_lat)
			poslon=''.join(compr_lon)
			
			#if (heading > 0 or speed > 0):
			#    if (heading >=360):
			#        c = '!'
			#    else:
			#        c = chr(int(heading/4)+33)
			#    s = chr(int(math.log(speed+1)/math.log(1.08)+33)) #not sure here...
			#    t='Y' #[
			#else:
			c=' '
			s=' '
			t=' '
	
			#packet = path + aprs_data_type + aprs_table_overlay + poslat + poslon + aprs_symbol + c + s + t 
			packet = object_type + object_name + object_alive + object_timestamp + object_sym_tbl + poslat + poslon + object_sym_code + c + s + t + object_comment
			print path+packet
			self.main.notify_show("Sending %s" % object_name, 2)
			self.main.aprs.msg_check(path+packet)
			self.main.aprs.send_data(packet)
			
		elif object_type=="query":
			callsign=object_name.ljust(9)
			packet=":%s:?APRS%s" % (callsign, object_comment)
			self.main.notify_show("Sending query %s" % callsign, 2)
			print packet
			self.main.aprs.msg_check(path+packet)
			self.main.aprs.send_data(packet)

        	
    	    #if (str(label_callsign.entry_get())<>'') and str(label_text.entry_get()<>''):
            #	self.main.aprs.send_message(str(label_callsign.entry_get()), str(label_text.entry_get()))
            #self.send_data(":%s:%s{%s}%s" % (call.ljust(9), message, sequence, replyack))
            #self.main.aprs.send_data(":%s:?APRS%s" % (callsign.ljust(9), query))
            
	
	btn_r._callback_add('clicked',send_object)

        self.main.pager.content_push(self.box)
                                                
    def prepare_object(self, button, name, comment='', obj_type='', lat='', lon=''):
    	global VIEW_STATION
    	VIEW_STATION=''
    	entry_name.entry_set(name)
    	entry_comment.entry_set(comment)
    	entry_lat.entry_set(lat)
    	entry_lon.entry_set(lon)
    	hs_type.label_set(obj_type)
    	
    	self.main.toolbar_item_create_object.selected=True

	
class StationsPage(object):
    def __init__(self, main):
        self.main = main
        global STATION_LIST


        # main box
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

#        label = elementary.Label(self.main.win)
#        label.label_set('<b>%s %s</>' % (appname, appversion))
#        label.size_hint_weight_set(0, 0)
#        label.size_hint_align_set(0.5, 0.5)
#        self.box.pack_end(label)
#        label.show()

        scroller = elementary.Scroller(self.main.win)
        scroller.bounce_set(False, True)
        scroller.size_hint_weight_set(1.0, 1.0)
        scroller.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(scroller)
        scroller.show()

        self.box2 = elementary.Box(self.main.win)
        self.box2.size_hint_weight_set(1, 1)
        self.box2.size_hint_align_set(-1, -1)
        scroller.content_set(self.box2)
        self.box2.show()
	
	#home location
	self.render_station_controll_buttons()	
	#STATION_LIST[fromcall]=[0,fromcall,time.time(), time.time(), rest_status,rest_speed,rest_course,rest_lat,rest_lon,rest_comment,1,0,0,0]
        # STATION,( buble0, text1, first seen2, last seen3, status4,speed5, course6,lat7,lon8,comment9,packet count10,distance11,text label12)
	STATION_LIST['HOME']=[0,'HOME',time.time(),time.time(), 'Home station', 0,0,home_qth[0], home_qth[1],'Homestation',0,0,0,0,0,'station','','','/','P']
	but, tex=self.render_station_button('HOME')
	STATION_LIST['HOME'][0]=but
	STATION_LIST['HOME'][11]=tex
    	coordinates=self.main.aprs.get_position("distance")
	
	self.update_station(but,'HOME',coordinates)

        self.main.pager.content_push(self.box)


    def update_station(self, detailbutton, callsign, coordinates, *args, **kargs):
    	  distance_=""
	  speed_=""
	  
	  if STATION_LIST[callsign][7]<>'' or STATION_LIST[callsign][8]<>'':
	      distance_ = self.get_distance(STATION_LIST[callsign][7], STATION_LIST[callsign][8], coordinates)
	      #print "dist tady:", distance_
	      if distance_ <> 0.0:
	          distance_=str(distance_) + 'km'
	          #print "dist s km:", distance_
	      else:
	      	  distance_=''
	      
	  if STATION_LIST[callsign][5]<>'':
	      speed_ = int(STATION_LIST[callsign][5])
	      if speed_ > 0:
	      	  speed_=str(round(speed_,0)) + 'km/h'
	      else:
	  	  speed_=''

	  icon = elementary.Icon(self.main.win)
	  if (time.time()-STATION_LIST[callsign][3]) < 300:
	      icon.file_set(DATA_DIR + "images/bulb-on.png")
      	  else:
	      icon.file_set(DATA_DIR + "images/bulb-off.png")
	  
	  if (time.time()-STATION_LIST[callsign][3]) > timeout * 60:
	      if callsign <> 'HOME':
    	          STATION_LIST[callsign][11].delete()
	          #del STATION_LIST[callsign][11]
	          STATION_LIST[callsign][13]=1
	      
	  detailbutton.icon_set(icon)
	  icon.show()
	  icon = elementary.Icon(self.main.win)
	  
	  
	  symbol=self.get_symbol(callsign)
	  icon.file_set(DATA_DIR + "images/symbols/%s" % symbol)
	  symbolbutton.icon_set(icon)
	  icon.show()

    	  detailbutton.label_set("%s %s %s" %(callsign, distance_, speed_))
    	  

    def create_message(self, button, callsign):
	  self.main.create_message_page.prepare_message(self, callsign)

    def get_distance(self, lat, lon, coordinates):
    	#print "getting distance"
	curent_position=coordinates
            
        #print "get distance coordinates 2:", curent_position
        try:
	    #print "calculating distance from: ", lat, lon
	    #print "to:                        ",curent_position[0],curent_position[1]
	    degrees_to_radians = math.pi/180.0
	    phi1 = (90.0 - float(curent_position[0]))*degrees_to_radians
	    phi2 = (90.0 - lat)*degrees_to_radians
	    theta1 = (float(curent_position[1]))*degrees_to_radians
	    theta2 = lon*degrees_to_radians
	    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2))
	    arc = math.acos( cos )
	    rest_distance=round(arc*6373,0)
        except:
	    print "distance calc error"
        #print rest_distance
        return rest_distance
    

    def get_symbol(self,callsign,*xargs):
    	    #print callsign
    	    SYMBOLS=r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  """
	    TABLES='/\\'
    	    symbolcode=SYMBOLS.find(STATION_LIST[callsign][18])
    	    symboltable=TABLES.find(STATION_LIST[callsign][19])
    	    symboltable+=1
    	    if symboltable<1:
    	    	    symboltable=1
    	    symbol="t%ss%s.png" %(symboltable,symbolcode)
    	    #print symbol
    	    return symbol
        	
        	
    def block_station(self,obj,callsign):
    	global VIEW_STATION
    	VIEW_STATION=''
    	global STATION_LIST
    	#print "-----------------------blocking", STATION_LIST[callsign][11]
	#textbox.delete()
	try:
	    STATION_LIST[callsign][11].delete()
        except:
            pass
	#del textbox
	STATION_LIST[callsign][12]=[1]
	STATION_LIST[callsign][13]=[1]

    def hide_station(self,obj,callsign):
    	global VIEW_STATION
    	VIEW_STATION=''
    	global STATION_LIST
    	#print "------------------------hiding", STATION_LIST[callsign][11]
    	#textbox.delete()
    	try:
    	    STATION_LIST[callsign][11].delete()
    	except:
    	    pass
    	#del textbox
    	STATION_LIST[callsign][13]=[1]


    def render_station_button(self, callsign, *args, **kargs):
      #fromcall,rest_status,rest_speed,rest_course,rest_lat,rest_lon,rest_comment,1)
	  #check if station is already in the list
	  textbox = elementary.Box(self.main.win)
	  textbox.horizontal_set(1)




	  #hide for now to gain some space
	  ##blockbutton = elementary.Button(self.main.win)
	  ##blockbutton.label_set("B")
	  ##blockbutton.callback_clicked_add(self.block_station,callsign)
	  ##blockbutton.show()
	  ##blockbutton.size_hint_weight_set(0.0, 0.0)
	  ##blockbutton.size_hint_align_set(-1.0, -1.0)
	  #icon = elementary.Icon(self.main.win)
	  #icon.file_set("/usr/share/atrack/images/edit-clear.png")
	  #blockbutton.icon_set(icon)
	  #blockbutton.scale_set(4)
	  #icon.show()

	  ##hidebutton = elementary.Button(self.main.win)
	  ##hidebutton.label_set("H")
	  ##hidebutton.callback_clicked_add(self.hide_station,callsign)
	  ##hidebutton.show()
	  ##hidebutton.size_hint_weight_set(0.0, 0.0)
	  ##hidebutton.size_hint_align_set(-1.0, -1.0)
	  #icon = elementary.Icon(self.main.win)
	  #icon.file_set("/usr/share/atrack/images/edit-clear.png")
	  #hidebutton.icon_set(icon)
	  #clearbutton.scale_set(4)
	  #icon.show()
	  global symbolbutton 
	  symbolbutton = elementary.Button(self.main.win)
	  #symbolbutton.label_set("H")
	  #symbolbutton.callback_clicked_add(self.hide_station,callsign)
	  symbolbutton.show()
	  symbolbutton.size_hint_weight_set(0.0, 0.0)
	  symbolbutton.size_hint_align_set(-1.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/edit-clear.png")
	  symbolbutton.icon_set(icon)
	  #symbolbutton.scale_set(4)
	  icon.show()
	
	  
	  self.detailbutton = elementary.Button(self.main.win)
	  self.detailbutton.label_set("%s" %(callsign))
	  #detailbutton.callback_clicked_add(self.show_station_details,callsign)
	  
	  #self.detailbutton._callback_add("clicked", self.change_station_details,callsign)
	  self.detailbutton._callback_add("clicked",self.show_station_details,callsign)

	  self.detailbutton.show()
	  self.detailbutton.size_hint_weight_set(1.0, 0.0)
	  self.detailbutton.size_hint_align_set(-1.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  #print time.time(), STATION_LIST[callsign][2]
	  if (time.time()-STATION_LIST[callsign][2]) < 300:
	      icon.file_set(DATA_DIR + "images/bulb-on.png")
      	  else:
	      icon.file_set(DATA_DIR + "images/bulb-off.png")
	  self.detailbutton.icon_set(icon)
	  icon.show()
	  
	  icon = elementary.Icon(self.main.win)
	  symbol=self.get_symbol(callsign)
	  icon.file_set(DATA_DIR + "images/symbols/%s" % symbol)
	  symbolbutton.icon_set(icon)
	  icon.show()

	  textbox.size_hint_weight_set(-1.0, 0.0)
	  textbox.size_hint_align_set(-1.0, -1.0)
	  #textbox.pack_start(deletebutton)
	  ##textbox.pack_start(hidebutton)
	  ##\textbox.pack_start(blockbutton)
	  textbox.pack_start(self.detailbutton)
	  textbox.pack_start(symbolbutton)
	  
  	  self.box2.pack_start(textbox)
	  textbox.show()
	  return self.detailbutton,textbox

    def show_station_details(self,button,callsign, *args, **kargs):
	  self.main.station_details_page.prepare_show_station_details(self, callsign,None)
	  
 	  
    def render_station_controll_buttons(self, *args, **kargs):

	  textbox = elementary.Box(self.main.win)
	  textbox.horizontal_set(1)

	  def block_all_stations(self):
	      global STATION_LIST
	      for i in STATION_LIST.keys():
	          if i <> 'HOME':
	      	      if not STATION_LIST[i][13]:
	      	          STATION_LIST[i][11].delete() #delete from list
	      	          #del STATION_LIST[i][11]
	      	          #print "deleting", i
	      	          STATION_LIST[i][12]=[1] #set as blocked
	      	          STATION_LIST[i][13]=[1] #set as hidden
	      	      

	  def clear_all_stations(self):
	      global STATION_LIST
	      for i in STATION_LIST.keys():
	      	  if i <> 'HOME':
	      	      if not STATION_LIST[i][13]:
	      	          STATION_LIST[i][11].delete()
	      	          STATION_LIST[i][13]=[1] #set as hidden

      
	  blockbutton = elementary.Button(self.main.win)
	  blockbutton.label_set("B")
	  blockbutton.callback_clicked_add(block_all_stations)
	  blockbutton.show()
	  blockbutton.size_hint_weight_set(1.0, 0.0)
	  blockbutton.size_hint_align_set(-1.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/edit-clear.png")
	  blockbutton.icon_set(icon)
	  #blockbutton.scale_set(4)
	  icon.show()

	  
	  unblockbutton = elementary.Button(self.main.win)
	  unblockbutton.label_set("UB")
	  unblockbutton.callback_clicked_add(self.unblock_all_stations)
	  unblockbutton.show()
	  unblockbutton.size_hint_weight_set(1.0, 0.0)
	  unblockbutton.size_hint_align_set(-1.0, -1.0)
	  #icon = elementary.Icon(self.main.win)
	  #icon.file_set("/usr/share/atrack/images/dialog-information.png")
	  #unblockbutton.rotation_set(30)
	  #unblockbutton.scale_set(1.5)
	  #unblockbutton.icon_set(icon)
	  #icon.show()

	  clearbutton = elementary.Button(self.main.win)
	  clearbutton.label_set("H")
	  clearbutton.callback_clicked_add(clear_all_stations)
	  clearbutton.show()
	  clearbutton.size_hint_weight_set(1.0, 0.0)
	  clearbutton.size_hint_align_set(-1.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/edit-clear.png")
	  clearbutton.icon_set(icon)
	  #clearbutton.scale_set(4)
	  icon.show()
	  
	  showbutton = elementary.Button(self.main.win)
	  showbutton.label_set("UH")
	  showbutton.callback_clicked_add(self.show_all_stations)
	  showbutton.show()
	  showbutton.size_hint_weight_set(1.0, 0.0)
	  showbutton.size_hint_align_set(-1.0, -1.0)
	  icon = elementary.Icon(self.main.win)
	  icon.file_set(DATA_DIR + "images/edit-show.png")
	  showbutton.icon_set(icon)
	  #showbutton.scale_set(4)
	  icon.show()
	  
	  
	  textbox.size_hint_weight_set(-1.0, 0.0)
	  textbox.size_hint_align_set(-1.0, -1.0)
	  #textbox.pack_start(deletebutton)
	  textbox.pack_start(clearbutton)
	  textbox.pack_start(showbutton)	  
	  textbox.pack_start(blockbutton)  
	  textbox.pack_start(unblockbutton)  
	  
  	  self.box2.pack_start(textbox)
	  textbox.show()
	  #return detailbutton

    def unblock_all_stations(self, *args):
    	global STATION_LIST
    	#unblock and show all stations
        for i in STATION_LIST.keys():
            if STATION_LIST[i][13]:
                STATION=STATION_LIST[i]
                but,tex=self.main.stations_page.render_station_button(i)
	        STATION_LIST[i][0]=but
	        STATION_LIST[i][11]=tex
	        STATION_LIST[i][12]=0
	        STATION_LIST[i][13]=0
	        

    def show_all_stations(self, *args):
    	global STATION_LIST
    	#show all non blocked stations
        for i in STATION_LIST.keys():
            if STATION_LIST[i][13] and not STATION_LIST[i][12]:
                STATION=STATION_LIST[i]
                but,tex=self.main.stations_page.render_station_button(i)
	        STATION_LIST[i][0]=but
	        STATION_LIST[i][11]=tex
	        STATION_LIST[i][12]=0
	        STATION_LIST[i][13]=0

class StationDetailsPage(object):
	
    def __init__(self, main):
        self.main = main
        # main box 
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

        scroller = elementary.Scroller(self.main.win)
        scroller.bounce_set(False, True)
        scroller.size_hint_weight_set(1.0, 1.0)
        scroller.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(scroller)
        scroller.show()
        
        self.box3 = elementary.Box(self.main.win)
        self.box3.size_hint_weight_set(1, 1)
        self.box3.size_hint_align_set(-1, -1)
        scroller.content_set(self.box3)
        self.box3.show()

	global label
        label = elementary.Label(self.main.win)
        #label.label_set('%s' % (about))
        label.size_hint_weight_set(1, 0)
        label.size_hint_align_set(0.5, 0.5)
        #label.scale_set(2)
        self.box3.pack_start(label)
        label.show()

        #box.pack_end(entry)
        global boxbuttons
        boxbuttons = elementary.Box(self.main.win)
        boxbuttons.size_hint_weight_set(1.0, 0)
        boxbuttons.horizontal_set(True)
        boxbuttons.homogenous_set(True)
	boxbuttons.size_hint_align_set(-1, -1)
        boxbuttons.show()

        global messagebutton
	messagebutton = elementary.Button(self.main.win)
	messagebutton.label_set("Msg")
	messagebutton.show()
	messagebutton.size_hint_weight_set(1.0, 0.0)
	messagebutton.size_hint_align_set(-1.0, -1.0)

        global editbutton
	editbutton = elementary.Button(self.main.win)
	editbutton.label_set("Edt")
	editbutton.show()
	editbutton.size_hint_weight_set(1.0, 0.0)
	editbutton.size_hint_align_set(-1.0, -1.0)
	
	global viewbutton
	viewbutton = elementary.Button(self.main.win)
	viewbutton.label_set("Web")
	viewbutton.show()
	viewbutton.size_hint_weight_set(1.0, 0.0)
	viewbutton.size_hint_align_set(-1.0, -1.0)

	global mapbutton
	mapbutton = elementary.Button(self.main.win)
	mapbutton.label_set("Map")
	mapbutton.show()
	mapbutton.size_hint_weight_set(1.0, 0.0)
	mapbutton.size_hint_align_set(-1.0, -1.0)


	global querybutton
	querybutton = elementary.Button(self.main.win)
	querybutton.label_set("Qry")
	querybutton.show()
	querybutton.size_hint_weight_set(1.0, 0.0)
	querybutton.size_hint_align_set(-1.0, -1.0)
	
	global blockmebutton
	blockmebutton = elementary.Button(self.main.win)
	blockmebutton.label_set("Blc")
	blockmebutton.show()
	blockmebutton.size_hint_weight_set(1.0, 0.0)
	blockmebutton.size_hint_align_set(-1.0, -1.0)
	
	global clearmebutton
	clearmebutton = elementary.Button(self.main.win)
	clearmebutton.label_set("Hid")
	clearmebutton.show()
	clearmebutton.size_hint_weight_set(1.0, 0.0)
	clearmebutton.size_hint_align_set(-1.0, -1.0)

        backbox = elementary.Box(self.main.win)
        backbox.size_hint_weight_set(1.0, 0)
        backbox.horizontal_set(True)
        backbox.homogenous_set(True)
	backbox.size_hint_align_set(-1, -1)
        backbox.show()

	detailbutton = elementary.Button(self.main.win)
	detailbutton.label_set("Back")
	detailbutton.callback_clicked_add(self.back)
	detailbutton.show()
	detailbutton.size_hint_weight_set(1.0, 0.0)
	detailbutton.size_hint_align_set(-1.0, -1.0)
	
	##global updatebutton
	##updatebutton = elementary.Button(self.main.win)
	##updatebutton.label_set("Update")
	##updatebutton.show()
	##updatebutton.size_hint_weight_set(1.0, 0.0)
	##updatebutton.size_hint_align_set(-1.0, -1.0)
	
	#icon = elementary.Icon(self.main.win)
	#icon.file_set("/usr/share/atrack/images/dialog-information.png")
	#detailbutton.icon_set(icon)
	#icon.show()

	boxbuttons.pack_end(messagebutton)
	boxbuttons.pack_end(editbutton)
	
	boxbuttons.pack_end(viewbutton)
	boxbuttons.pack_end(mapbutton)
	
	boxbuttons.pack_end(querybutton)
	boxbuttons.pack_end(clearmebutton)
	boxbuttons.pack_end(blockmebutton)
	
	##backbox.pack_end(updatebutton)
	backbox.pack_end(detailbutton)
	
	self.box3.pack_end(boxbuttons)
	self.box3.pack_end(backbox)
	
	
  	  
        self.main.pager.content_push(self.box)


    def back(self,*args, **kargs):
    	  global VIEW_STATION
    	  VIEW_STATION=''
	  
	  self.main.kill_station_details_page()
	  #self.main.make_station_details()
	  self.main.show_stations_page()



    def prepare_show_station_details(self,button, callsign,coordinates=None, *args, **kargs):
    	self.main.make_station_details()
	global VIEW_STATION
    	VIEW_STATION=callsign
    	#print "update station preview ", callsign
    	about=""
    	label.label_set('')
    	distance_=""
	speed_=""
	#print "getting coordinates"
    	coordinates=self.main.aprs.get_position("distance")
	#print coordinates    
	if STATION_LIST[callsign][7]<>'' or STATION_LIST[callsign][8]<>'':
	    distance_ = self.main.stations_page.get_distance(STATION_LIST[callsign][7], STATION_LIST[callsign][8], coordinates)
	    #print "dist tady:", distance_
	    distance_=str(distance_) + 'km'
	
	#print "distance ", distance_
	if callsign in STATION_LIST:
	 about = str(STATION_LIST[callsign][17]) + " <b>" + callsign + " " + str(STATION_LIST[callsign][16]) + "</b> " + str(STATION_LIST[callsign][4])+ "<br><br>\
	 <b>first seen:</b> " + time.strftime('%H:%M:%S',time.localtime((STATION_LIST[callsign][2]))) + " (" + time.strftime('%H:%M:%S',time.gmtime((time.time()-STATION_LIST[callsign][2]))) + ")<br>\
	 <b>last seen:</b> " + time.strftime('%H:%M:%S',time.localtime((STATION_LIST[callsign][3]))) + " (" + time.strftime('%H:%M:%S',time.gmtime((time.time()-STATION_LIST[callsign][3]))) + ")<br>\
	 <b>Packets:</b> " + str(STATION_LIST[callsign][10]) + "<br><br>\
	 <b>Comment:</b> " + str(STATION_LIST[callsign][9]) + "<br>\
	 <b>Speed:</b> " + str(STATION_LIST[callsign][5]) + "<br>\
	 <b>Distance:</b> " + distance_ + "<br>\
	 <b>Course:</b> " + str(STATION_LIST[callsign][6]) + "<br>\
	 <b>Altitude:</b> " + str(STATION_LIST[callsign][14]) + "<br>\
	 <b>Lat:</b> " + str(STATION_LIST[callsign][7]) + "<br><p>\
	 <b>Lon:</b> " + str(STATION_LIST[callsign][8]) + "<br><p>"
	 
	label.label_set('%s' % (about))
        messagebutton.callback_clicked_add(self.main.create_message_page.prepare_message, callsign)
        
        if STATION_LIST[callsign][15]=='item' or STATION_LIST[callsign][15]=='object': #if station
            editbutton.show()
            #boxbuttons.pack_after(editbutton,messagebutton)
            boxbuttons.unpack(querybutton)
            querybutton.hide()
    	    editbutton.callback_clicked_add(self.main.create_object_page.prepare_object, callsign, str(STATION_LIST[callsign][9]),str(STATION_LIST[callsign][15]),str(STATION_LIST[callsign][7]),str(STATION_LIST[callsign][8]))
        else:        	
            boxbuttons.unpack(editbutton)
	    editbutton.hide()
	    querybutton.show()
	    #boxbuttons.pack_after(querybutton,mapbutton)
	    querybutton.callback_clicked_add(self.main.create_object_page.prepare_object, callsign, 'P', 'Query')
            
        viewbutton.callback_clicked_add(self._open_aprs, callsign)
        blockmebutton.callback_clicked_add(self.main.stations_page.block_station, callsign)
        clearmebutton.callback_clicked_add(self.main.stations_page.hide_station, callsign)
        blockmebutton.callback_clicked_add(self.main.show_stations_page)
        clearmebutton.callback_clicked_add(self.main.show_stations_page)
        
        mapbutton.callback_clicked_add(self.showmap,callsign)
        

        
        ##updatebutton.callback_clicked_add(self.show_station_details, VIEW_STATION,None, None)
        
    	self.main.show_station_details_page()

    def _open_aprs(self, button, url):
        import subprocess
        url="http://aprs.fi/static/%s" % url
        cmd = None
        if os.path.exists("/usr/bin/eve"):
            cmd = ["/usr/bin/eve"]
        elif os.path.exists("/usr/bin/ventua"):
            cmd = ["/usr/bin/ventura"]
        elif os.path.exists("/usr/bin/firefox"):
            cmd = ["/usr/bin/firefox"]
        elif os.path.exists("/usr/bin/midori"):
            cmd = ["/usr/bin/midori"]
        elif os.path.exists("/usr/bin/dillo"):
            cmd = ["/usr/bin/dillo"]
        elif os.path.exists("/usr/bin/xdg"):
            cmd = ["/usr/bin/xdg-open"]
        if cmd:
            cmd.append(url)
            subprocess.Popen(cmd)
            

	        
            
    def showmap(self, object, callsign, *xargs):
    	import tempfile
    
        def get_map(calsign,zoom=None):
		#print callsign
		if callsign in STATION_LIST:
		    if zoom==None:
			zoom=12
		    #savefile = open("%s-%s-%s.png" % (zoom,xtile,ytile), "w")
		    savefile=tempfile.NamedTemporaryFile(suffix='.png',delete=False)
		    #url = "http://tile.openstreetmap.org/%s/%s/%s.png" % (str(zoom), str(xtile), str(ytile))r
		    url="http://ojw.dev.openstreetmap.org/StaticMap/?show=1&lat=%s&lon=%s&zoom=%s&h=300&w=300&layer=mapnik&fmt=png&mlat0=%s&mlon0=%s&mico0=%s" % (str(STATION_LIST[callsign][7]), str(STATION_LIST[callsign][8]),zoom,str(STATION_LIST[callsign][7]), str(STATION_LIST[callsign][8]),'0')
		    #print url
		    savefile.write(urllib.urlopen(url).read())
		    a=savefile.name
		    #print a
		    bgg.file_set(a)
		    #savefile.close()
		    
     	def ca_cancel(self):
    	    map_win.hide()
    	    map_win.delete()
    	    #del map_win
    	    
        map_win = elementary.Window('title', elementary.ELM_WIN_BASIC)
    	map_win.callback_destroy_add(ca_cancel)
    	#map_win.title_set('%s' % title)
    	
	bgg = elementary.Background(map_win)
        #bgg.file_set("10-20-20.png")
        #map_win._callback_add("clicked", ca_cancel)
	map_win.resize_object_add(bgg)
	map_win.resize(480,640)
        map_win.autodel_set(True)
        #map_win.fullscreen_set(True)
        bgg.size_hint_weight_set(1.0, 1.0)
        
        bgg.show()

	box = elementary.Box(map_win)
        box.size_hint_weight_set(1, 1)
        box.size_hint_align_set(-1, -1)
        box.show()
        map_win.resize_object_add(box)

        emptybox = elementary.Box(map_win)
        emptybox.size_hint_weight_set(1.0, 10)
        emptybox.horizontal_set(True)
        emptybox.homogenous_set(True)
	emptybox.size_hint_align_set(-1, -1)
        emptybox.show()

        boxbuttons = elementary.Box(map_win)
        boxbuttons.size_hint_weight_set(0, 0)
        boxbuttons.horizontal_set(True)
        boxbuttons.homogenous_set(True)
	boxbuttons.size_hint_align_set(-1, -1)
        boxbuttons.show()

	plusbutton = elementary.Button(map_win)
	plusbutton.label_set("+")
	plusbutton.show()
	plusbutton.size_hint_weight_set(1.0, 0.0)
	plusbutton.size_hint_align_set(-1.0, -1.0)

	minusbutton = elementary.Button(map_win)
	minusbutton.label_set("-")
	minusbutton.show()
	minusbutton.size_hint_weight_set(1.0, 0.0)
	minusbutton.size_hint_align_set(-1.0, -1.0)


	closebutton = elementary.Button(map_win)
	closebutton.label_set("Close")
	closebutton.show()
	closebutton.size_hint_weight_set(1.0, 0.0)
	closebutton.size_hint_align_set(-1.0, -1.0)
	closebutton.callback_clicked_add(ca_cancel)
	
	
	#boxbuttons.pack_end(plusbutton)
	#boxbuttons.pack_end(minusbutton)
	boxbuttons.pack_end(closebutton)
	
	box.pack_end(emptybox)
	box.pack_end(boxbuttons)
	
	map_win.show()
	get_map(callsign)
  
    
    
    
    def send_query(self, object, callsign, query):
    	    #print callsign, query
    	    self.main.aprs.send_data(":%s:?APRS%s" % (callsign.ljust(9), query))
    

class AboutPage(object):
    def __init__(self, main):
        self.main = main

        # main box
        self.box = elementary.Box(self.main.win)
        self.box.size_hint_weight_set(1, 1)
        self.box.size_hint_align_set(-1, -1)
        self.box.show()

        label = elementary.Label(self.main.win)
        label.label_set('<b>%s %s</>' % (appname, appversion))
        label.size_hint_weight_set(0, 0)
        label.size_hint_align_set(0.5, 0.5)
        self.box.pack_end(label)
        label.show()

        scroller = elementary.Scroller(self.main.win)
        scroller.bounce_set(False, True)
        scroller.size_hint_weight_set(1.0, 1.0)
        scroller.size_hint_align_set(-1.0, -1.0)
        self.box.pack_end(scroller)
        scroller.show()

        box = elementary.Box(self.main.win)
        box.size_hint_weight_set(1, 1)
        box.size_hint_align_set(-1, -1)
        scroller.content_set(box)
        box.show()

        about  = "<b>aTrack is Python Elementary based APRS tool</b> <br><br>Copyright (c) 2009-2010 Petr Vanek<br>License GNU GPL v3<br><br>"
        about+= elementary.Entry.utf8_to_markup("""A TODO list in random order:
        - fix GLOBAL VARIABLES (this is getting better already)
        - animate status
        - continue extending python aprs parser
        - externalize the aprs parser and modify all functions to use it
	""")
        
        entry = elementary.Entry(self.main.win)
        entry.editable_set(False)
        entry.line_wrap_set(True)
        entry.size_hint_weight_set(1, 1)
        entry.size_hint_align_set(-1, -1)
        entry.entry_set(about)
        box.pack_end(entry)
        entry.show()

        links = [
            (
                'http://atrack.googlecode.com',
                "[1] : <a href=\"%s\"><link>aTrack</></a> project homepage",
                ),
            (
                'http://aprs.fi',
                "[2] : <a href=\"%s\"><link>APRS.fi</></a> Google Maps APRS."
                ),
            (
                'http://aprs.fi/static/' + username,
                "[3] : <a href=\"%s\"><link>" + username+ "</></a> on Google Maps APRS."
                )
                        
            
            
            ]
        for link in links:
            anchor = elementary.AnchorBlock(self.main.win)
            anchor.size_hint_weight_set(1, 1)
            anchor.size_hint_align_set(-1, -1)
            if link[0]:
                anchor.text_set(link[1] % link[0] + '<br><br>')
                anchor.callback_clicked_add(self._on_anchor_clicked, link[0])
            else:
                anchor.text_set(link[1] + '<br><br>')
            box.pack_end(anchor)
            anchor.show()

        self.main.pager.content_push(self.box)

    def _on_anchor_clicked(self, object, event, url):
        if url:
            #msg = 'Open url in browser?'
            self._open_url(url)

    def _open_url(self, url):
        import subprocess

        cmd = None
        if os.path.exists("/usr/bin/ventura"):
            cmd = ["/usr/bin/ventura"]
        elif os.path.exists("/usr/bin/browser"):
            cmd = ["/usr/bin/browser"]
        elif os.path.exists("/usr/bin/firefox"):
            cmd = ["/usr/bin/firefox"]
        elif os.path.exists("/usr/bin/midori"):
            cmd = ["/usr/bin/midori"]
        elif os.path.exists("/usr/bin/dillo"):
            cmd = ["/usr/bin/dillo"]
        elif os.path.exists("/usr/bin/xdg"):
            cmd = ["/usr/bin/xdg-open"]
        if cmd:
            cmd.append(url)
            subprocess.Popen(cmd)


class Aprs(object):
    
    def __init__(self, main):
        self.main = main
	self.sent_acks = {}
	self.recv_acks = {}
	self.seen_bulletins = {}
	self.bulletins = ["AIR", "DGPS", "QST", "TEL", "ALL", "DRILL", "QTH", "TEST", "AP", "DX", "RTCM", "TLM", "BEACON", "ID", "SKY", "WX", "CQ", "JAVA", "SPACE", "ZIP", "GPS", "MAIL", "SPC", "DF", "MICE", "SYM", "BLN", "NWS", "NTS"]
	#force_send = 0
	self.display_adresses=["ALL"]
	self.sequence = random.randrange(0, 7000)
        self.queue_list = {}
        self.message_list = {}
        self.current_message = {}
        self.current_message_text = {}
        self.current_message_count = {}
        self.current_message_delay = {}


 
    def get_position(self, service=None):
    	    #TODO unify functions for getting positions for different services
	    global status
            global now
            global unique_packet_new
            global heading_now
            # get gps data 
            position = POSITION 
            course = COURSE 
            #position = resources.position_iface.GetPosition() 
            #course = resources.course_iface.GetCourse() 

             
            # type of gps fix 
            if position[0] >= 3:
                     gps_fix = "2D"
            if  position[0] == 7:
                     gps_fix = "3D"
            if  position[0] < 3:
                     gps_fix = "No Fix" 
             

            # when got fix, check position 
            if  position[0] >= 3:
                    status="FIX: " + gps_fix 
                    #print gps_fix
                    gps_time = str(position[1])
                    gps_lat = str(position[2])
                    gps_long = str(position[3]) 
                    gps_alt = str(position[4])
		    #		print  gps_alt
		    #now = int(time.strftime('%H%M%S',time.localtime(position[1])))
		    #now = int(time.strftime('%H%M%S',time.localtime(time.time())))
		    now = time.time()
		    
		    #print "now", now

		    if service == "youloc":
		            #now = time.strftime('%H%M%S',time.localtime(position[1]))
		            heading = int(str(round(course[3],0)).split('.',1)[0])
		            speedy= int(str(round(course[2],0)).split('.',1)[0])
		            alt = str(round(position[4]*3.2808399,0)).split('.',1)[0]
			    altitude=alt.rjust(6,'0')
			    templat = float(gps_lat.replace(',', '.'))
			    templon = float(gps_long.replace(',', '.'))
		            packet={'userkey':__youloc_userkey__, 'lat':str(templat), 'lon':str(templon), 'alt':str(altitude), 'speed':str(speedy), 'course':str(heading)}
		            return packet

		    if service=="distance":
		            heading = int(str(round(course[3],0)).split('.',1)[0])
			    templat = float(gps_lat.replace(',', '.'))
			    templon = float(gps_long.replace(',', '.'))
		            packet=str(templat), str(templon), str(heading)
		            return packet


		    elif service == "locator":
    			    loclen=10 #length of locator qrid precision                          
                            maxn=loclen/2
			    lat=float(gps_lat)
			    lon=float(gps_long)

			    lon=(lon+180.0)/20                  # scale down and set up for first digit
			    lat=(lat+90.0)/10
			    mhloc=""
			    i=0
			    while i<maxn:
				i+=1
				loni=int(lon)
				lati=int(lat)
				if i%2:
				    mhloc+=chr(ord('A')+loni)+chr(ord('A')+lati)
				    lon=(lon-loni)*10
				    lat=(lat-lati)*10
				else:
				    mhloc+=str(loni)+str(lati)
				    lon=(lon-loni)*24
				    lat=(lat-lati)*24
			    
			    #print 'Locator: ', mhloc      # main output
		            return mhloc

		    else: #normal aprs compressed packet
		            heading = int(str(round(course[3],0)).split('.',1)[0])
			    heading_now=heading
		   	    #normal packet
		            speed = int(str(round(course[2],0)).split('.',1)[0])
		   	    #normal packet
		            alt = str(round(position[4]*3.2808399,0)).split('.',1)[0]
			    alt=alt.rjust(6,'0')
			    
			    templat = float(gps_lat.replace(',', '.'))
			    templon = float(gps_long.replace(',', '.'))
			    #compressed packet

			    compr_lat=self.compress_lat(templat)
			    compr_lon=self.compress_lon(templon)
			    poslat=''.join(compr_lat)
		 	    poslon=''.join(compr_lon)
			    #print "out: ", poslat, poslon
			    #decompress for test of the same values
			    #a=90-((((((((ord(compr_lat[0])-33)*91.0)+(ord(compr_lat[1])-33))*91.0)+(ord(compr_lat[2])-33))*91.0)+(ord(compr_lat[3])-33))/380926)
			    #b=180-((((((((ord(compr_lon[0])-33)*91.0)+(ord(compr_lon[1])-33))*91.0)+(ord(compr_lon[2])-33))*91.0)+(ord(compr_lon[3])-33))/190463)
			    #print a,b
			    if (heading > 0 or speed > 0):
				if (heading >=360):
				    c = '!'
				else:
				    c = chr(int(heading/4)+33)
			
				s = chr(int(math.log(speed+1)/math.log(1.08)+33)) #not sure here...
				t='Y' #[

			    else:
				c=' '
				s=' '
				t=' '

			    unique_packet_new = poslat + poslon
		            packet = path + aprs_data_type + aprs_table_overlay + poslat + poslon + aprs_symbol + c + s + t + '/A=' + alt + '' + comment + '\n'
			    return packet
		    
            else:# if no fix
         	    if service=="distance": #we will provide old valid coordinates. these are on the begining home_qth...
         	    	position=OLD_POSITION
         	    	gps_time = str(position[1])
                        gps_lat = str(position[2])
                        gps_long = str(position[3]) 
                        gps_alt = str(position[4])
		        heading = 0
			templat = float(gps_lat.replace(',', '.'))
			templon = float(gps_long.replace(',', '.'))
		        packet=str(templat), str(templon), str(heading)
		        return packet

                    gps_time = "" 
                    gps_lat = ""
                    gps_long = ""
                    gps_alt = ""
                    #print "no fix"
                    
                    status = "NO FIX"
                    packet = "nofix"
                    return packet



    def connect_aprs(self):

            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.main.main_page.status_write("connecting to aprs")
            try:
                iplist = socket.gethostbyname_ex(serverHost)[2]
            except socket.error, msg:
                self.main.main_page.status_write("\n%s\n" % msg[1])
                self.sock = None
            server = random.choice(iplist)
            self.main.main_page.status_write("to %s\n" % server)
            try:
                self.sock.connect((server, serverPort))
            except socket.error, msg:
                self.main.main_page.status_write("\n%s\n" % msg[1])
                self.sock = None
                self.reconnect_aprs()
	    self.main.main_page.toggle_con.state_set(True)
	    self.main.main_page.status_write("Connected")

            response = self.sock.recv(recvbuffer)
            self.main.main_page.status_write("%s" % response)
            #javaprs server only
            #if (response.find("javAPRSSrvr") == -1):
            #    self.main.main_page.status_write("not javAPRSSrvr")
            #    self.reconnect_aprs()

            if (response.find("Port Full") != -1):
                self.main.main_page.status_write("Port Full")
                self.reconnect_aprs()

            sendme ='user ' + str(username) + ' pass ' + str(password) + ' vers ' + str(appname) + ' ' + str(appversion) + ' filter ' + str(aprsfilter) + '\n'
            self.sock.sendall(sendme)

            response = self.sock.recv(recvbuffer)
            self.fdh = ecore.fd_handler_add(self.sock, ecore.ECORE_FD_READ, self.recv_data)
            #javaprs server only
            #self.main.main_page.status_write("%s" % response)
            #if (response.find("# logresp") == -1):
            #    self.main.main_page.status_write("invalid response")
            #    self.reconnect_aprs()

            if (response.find("unverified") == 1) or (response.find("Unverified") == 1):
                sendme = "# filter %s\n" % aprsfilter
                self.sock.sendall(sendme)
                self.main.main_page.status_write("unverified %s " % sendme)
                self.main.notify_show("Logged in as NO CALL!", 5)
            #if (response.find("%s verified" % username) == -1) or (response.find("Verified user %s" % username) == -1) :
            # 	print response
            #    self.main.main_page.status_write("not verified")
            #    self.reconnect_aprs()

	    if (response.find("%s verified" % username) != -1):
                #print "reset connect retry"
		global connect_retry
            	connect_retry=10 #reset for next connect

            #self.main.main_page.status_write("\n")



    def disconnect_aprs(self):
        self.main.main_page.status_write("disconnecting")
	self.main.main_page.toggle_con.state_set(False)
        self.sock.close()
	self.fdh.delete()
	    
    def reconnect_aprs(self):
    	global connect_retry
	print "reconnecting ", connect_retry
        try:
            self.sock.close()
            self.fdh.delete()
        except socket.error, msg:
            self.main.main_page.status_write("\n%s\n" % msg[1])
            self.sock = None
        
        
        if connect_retry>0:
	    connect_retry=connect_retry-1
	    self.main.main_page.status_write("reconnecting %s" % connect_retry)
	    self.connect_aprs()
        else:
            #reset	
            self.main.main_page.status_write("disconnected")
            self.main.main_page.toggle_con.state_set(False)
            

    def petr (self, fdh):
	print "jojo"
	print "self: " , self
	print "fdh: ", fdh
	print self.sock.recv(recvbuffer)
	return True

    def send_data(self, msg, *args):
        if (self.sock == None):
            self.reconnect_aprs()
            #return False
        try:
	    #self.main.main_page.status_write("%s%s" % (path, msg))
            self.sock.sendall("%s%s\n" % (path, msg))
        except:
            self.main.main_page.status_write("Problem sending packet\n")
            self.sock = None
            self.reconnect_aprs()
            #return False
        #return True
        self.main.main_page.status_write("%s%s" % (path, msg))

    def send_ack(self, tocall, sequence):
        # should check for duplicate messages in the next 30 seconds and drop them
        # aprsd does this for us - but should do it here as well
        if (tocall in self.sent_acks):
            currentack = self.sent_acks[tocall]
            if (currentack == sequence):
                ackmessage = ":%s:ack%s" % (tocall.ljust(9), sequence)
                self.send_data(ackmessage)
        return False

    def recv_data(self, fdhandler):
            #global sock
	    #print fdhandler
            if (self.sock == None):
                return False
            while 1:
                try:
                    recv_data = self.sock.recv(recvbuffer)
                except:
                    self.main.main_page.status_write("Server closed connection.\n")
                    self.sock = None
                    self.reconnect_aprs()
                    return False
                if not recv_data:
                    self.main.main_page.status_write("Server closed connection.\n")
                    self.sock = None
                    self.reconnect_aprs()
                    return False
                else:
                    # sometimes more than one packet comes in
                    for packet in recv_data.split("\n"):
                    	#print time.strftime('%H%M%S',time.localtime(time.time())), packet
                        if (len(packet) < 2):
			    break
                            
                        # find uri's http or www
                        #webaddy = packet.lower().find("http")
                        #if (webaddy != -1):
                        #    packet = ("%s\n%s" % (packet[:webaddy], packet[webaddy:]))
                        #else:
                        #    webaddy = packet.lower().find("www")
                        #    if (webaddy != -1):
                        #        packet = ("%s\n%s" % (packet[:webaddy], packet[webaddy:]))
                        if (packet[0] == "#"):
                            #self.status_write("%s\n" % packet)
			    pass
		    	    
                        else:
                            #cuthere = packet.find(":")
                            #self.status_write("%s\n" % packet[:cuthere+1])
                            #self.status_write("%s\n" % packet[cuthere+1:])
                            self.msg_check(packet)
			    #print packet
			    
                    return True

    #packet = address + position + comment
    #print (packet) # prints the packet being sent
    #print (len(comment)) # prints the length of the comment part of the packet
    def msg_check(self, data):
	#self.main.main_page.status_write(data) #show incoming packets
        mycall = username.upper()
        firstcheck = data.find("::")# message?
        secondcheck = data[firstcheck+11:firstcheck+12]#looking for :
        thirdcheck = data.find("{")#looking for ack sign
        if (firstcheck != -1 and secondcheck == ":"): #if really a message
            tocall = data[firstcheck+2:firstcheck+11].upper() #adressee
            strippedtocall = tocall.strip() # stripped
            fromcall = data[:data.find(">")].upper() #caller
	    isbulletin = self.bulletin_check(strippedtocall)# is it a bulletin?
            # 'mycall' check allows people with bulletin looking calls to ack messages
            # this check does not fix the problem of sending messages to bulletin looking calls
            if (isbulletin and strippedtocall != mycall):#****************BULLETIN********************
                message = data[firstcheck+12:]#msg text
                #self.add_callsign(fromcall, False)
                bln_id = "%s-%s" % (fromcall, strippedtocall)#some id creation here
                # show bulletin if have never seen it or has been at least 1 day since last viewing
                #if (not bln_id in self.seen_bulletins or time.time() - self.seen_bulletins[bln_id] > 86400):
                    #self.seen_bulletins[bln_id] = time.time()
                self.main.messages_page.render_message("BLN: " + fromcall, time.strftime("%m/%d %H:%M", time.localtime()), strippedtocall, message)
		    #display popup with the bltn
            else:#************************MESSAGE****************
                #
		#print "got to istodisplaisy?"
                istodisplay = self.istodisplay_check(strippedtocall,self.display_adresses)
		#what adresses do we like to see (list: display_adresses)
		if (istodisplay):# displaying local traffic messages, not for us
			if (strippedtocall == mycall):#if for me
			    #self.add_callsign(fromcall, False)
		            if (thirdcheck != -1):#if asking for ack
		                sequence_end = data.find("}")#is there an end bracket?
		                if (sequence_end == -1):#if yes
		                    sequence = data[thirdcheck + 1:]#ack code is this
		                else:# second bracket missing
		                    sequence = data[thirdcheck + 1:sequence_end]#ack code is this
		                    replyack = data[sequence_end + 1:]#huh, looking for the second bracket again?
		                    if (len(replyack) > 1): # if there is a code to reply with
		                        ackid = "%s-%s" % (fromcall, replyack) # id of this message
		                        if (ackid in self.recv_acks): # if we have been replied
		                            if (self.recv_acks[ackid] == 0): #if not (or actually YES???

		                                count_start = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                                count_end = count_start.forward_search(">", gtk.TEXT_SEARCH_TEXT_ONLY)
		                                self.messagebuffer.delete(count_start, count_end[0])

		                                line_end = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                                queue_start = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                                line_end.forward_to_line_end()
		                                queue_start.forward_to_line_end()
		                                queue_start.backward_chars(12)
		                                self.messagebuffer.delete(queue_start, line_end)

		                                line_end = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                                line_end.forward_to_line_end()
		                                self.messagebuffer.insert(line_end, " <*ACKED*>")

		                                self.send_msg_queue(fromcall)
		                            self.recv_acks[ackid] = 1
		                message = data[firstcheck+12:thirdcheck] # text of message
				if (strippedtocall == mycall):#if the message was for me, send ack
				    ackmessage = ":%s:ack%s" % (fromcall.ljust(9), data[thirdcheck + 1:]) # ack message
				    #print "sending ack", ackmessage
		                    self.send_data(ackmessage)# send ack message
		                id = "%s-%s" % (fromcall, sequence)# create an id
		                if (id in self.sent_acks):# if we have sent ack, add timers to send ack not sure here... need to test 
				    ecore.timer_add(30, self.send_ack, tocall, sequence) #ecore glib call, in seconds
				    ecore.timer_add(60, self.send_ack, tocall, sequence) #ecore glib call
				    ecore.timer_add(120, self.send_ack, tocall, sequence) #ecore glib call
				    print "calling timer to send: ", self.send_ack, tocall, sequence
				    #gtk gobject
		                    #self.timers.append(gobject.timeout_add(30 * 1000, self.send_ack, tocall, sequence))
		                    #self.timers.append(gobject.timeout_add(60 * 1000, self.send_ack, tocall, sequence))
		                    #self.timers.append(gobject.timeout_add(120 * 1000, self.send_ack, tocall, sequence))
		                else:
		                    # TODO beep?
				    #MARK 2
		                    #self.show_message("<b>MESSAGE ASKING ACK</b><br>\n%s %s:%s><br>\n<br>\n %s\n" % (time.strftime("%m/%d %H:%M", time.localtime()), fromcall, strippedtocall, message))
				    self.main.messages_page.render_message(fromcall, time.strftime("%m/%d %H:%M", time.localtime()), strippedtocall, message)
				    self.main.notify_show("Message from " + fromcall, 90)
				    self.main.toolbar_item_messages.selected=True
				    #here check tor query but is less likely as this requires ask. perhaps add later
		                self.sent_acks[id] = time.time() # to help a cleanup thread later
		                self.sent_acks[fromcall] = sequence # to help with reply acks later
		            else:# if not asking for ack
		                message = data[firstcheck+12:]
		                if (message[0:3] == "ack"): #is this an ACK message?
		                    sequence_end = message.find("}")
		                    if (sequence_end == -1):
		                        sequence = message[3:]
		                    else:
		                        sequence = message[3:sequence_end]
		                    ackid = "%s-%s" % (fromcall, sequence)
		                    if (ackid in self.recv_acks):
		                        if (self.recv_acks[ackid] == 0):

		                            #count_start = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                            #count_end = count_start.forward_search(">", gtk.TEXT_SEARCH_TEXT_ONLY)
		                            #self.messagebuffer.delete(count_start, count_end[0])

		                            #line_end = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                            #queue_start = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                            #line_end.forward_to_line_end()
		                            #queue_start.forward_to_line_end()
		                            #queue_start.backward_chars(12)
		                            #self.messagebuffer.delete(queue_start, line_end)

		                            #line_end = self.messagebuffer.get_iter_at_mark(self.message_marks[ackid])
		                            #line_end.forward_to_line_end()
		                            #self.messagebuffer.insert(line_end, " <*ACKED*>")

		                            self.send_msg_queue(fromcall)
		                    self.recv_acks[ackid] = 1
		                else:
		                    # TODO beep?
				    #MARK1	
		                    self.main.messages_page.render_message(fromcall, time.strftime("%m/%d %H:%M", time.localtime()), strippedtocall, message)
		                    self.main.notify_show("Message from " + fromcall, 90)
		                    self.main.toolbar_item_messages.selected=True
		                    #print self.main.toolbar_item_messages.get_selected()
		                    # TODO query check
		                    if (message[0:5] == "?APRS"): # query
		                    	print message
		                    	global force_send
		                    	query_type=message[5]
		                    	print query_type
		                    	if query_type=="?": #general, pos and status
		                    		force_send=1
		                    		self.main.aprs.send_now()
		                    		self.main.preferences_page.send_status()
		                    	elif query_type=="P": #position
		                    		force_send=1
		                    		self.main.aprs.send_now()
		                    	elif query_type=="S": # status
		                    		self.main.preferences_page.send_status()
		                    		
		                    	#and message[-1] == "?"):
		                        pass
			else: # network traffic messages. don't ack but show if required...
			    #print "random traffic"
			    message = data[firstcheck+12:]
		            if (message[0:3] != "ack"):
		            	    
		            	self.main.messages_page.render_message(fromcall, time.strftime("%m/%d %H:%M", time.localtime()), strippedtocall, message)
        
        else: #not a message, keep parsing this packet	
            fromcall = data[:data.find(">")].upper() #caller
            pathcomponents=data[data.find(">")+1:data.find(":")].split(',')
            rest = data[data.find(":")+1:]
            #print fromcall, rest
            #check first character of the packet
            packettype=rest[0:1]
            paclen=len(rest)
            rest_status=''
            rest_course=''
            rest_speed=''
            rest_comment=''
            rest_lat=''
            rest_lon=''
	    rest_distance=''
	    rest_alt=''
	    rest_type=''
	    rest_alive=''
	    rest_name=''
	    symbolcode=''
	    symboltable=''
	    
            rest=rest.replace('\n', ' ')
            rest=rest.replace('\r', ' ')
            #normal or compressed location of station report
	    if packettype == '!' or packettype == '=' or packettype == '/' or packettype == '@':
	        if paclen >=14:
	            rest_type='station'
	            if packettype == '/' or packettype == '@':
			#timestamp, just skip it
			rest = rest[7:] #remove timestamp
		    rest=rest[1:] #remove firts char
		    # grab the ascii value of the first byte of body
		    poschar=ord(rest[0:1])
		    #print poschar
		    if poschar >= 48 and poschar <= 57 :
			#uncompressed location
			#print "normal location", fromcall
			#todo check for wearther stations
			if len(rest)>=19:
			    rest_lat, rest_lon, symbolcode, symboltable=self.normalpos_to_decimal(rest)
			    #position_to_decimal(rest)
			    rest=rest[19:]
			    #print rest
				
		    elif (poschar == 47 or poschar == 92 or (poschar >= 65 and poschar <= 90) or (poschar >= 97 and poschar <= 106)):
			if len(rest)>=13:
			    #print "decompressing"
			    #print "compressed location", fromcall
			    rest, symboltable, symbolcode, rest_lat, rest_lon, rest_course, rest_alt, rest_speed, rest_radiorange = self.compressed_to_decimal(rest)
			    #print fromcall, rest_speed			    
			    #compressed packed
		    if symbolcode <> '_':
		        rest, rest_course, rest_speed, rest_alt = self.comment_to_decimal(rest,rest_course, rest_speed, rest_alt)
			if len(rest)>0:
			    rest_comment=rest    
	
	    #weather report, parse later
	    elif packettype == ':':
	    	    rest_comment="weather, parse later"
	    	    #print "weather", fromcall
	    
	    #mice, parse later
    	    elif  (ord(packettype) == 0x27 or ord(packettype) == 0x60):
    	    	    #rest_comment="mice, parse later"
    	    	    if len(rest)>=9:
            	    	rest_type='station'
            	    	#print fromcall
            	    	destcallsign=self.check_ax25call(pathcomponents[0])
            	    	#print "II",destcallsign
    	    	        rest_lat, rest_lon, rest_speed, rest_alt, rest_comment, symbolcode, symboltable = self.mice_to_decimal(rest[1:], destcallsign, fromcall)
    	    	        
    	    	    #print "mic-e", fromcall
		#object	
            elif packettype == ';':
            	    #pass
            	    #print rest
            	    if len(rest)>=31:
            	    	rest_type='object'
            	        a=re.search('^;([\x20-\x7e]{9})(\*|_)(\d{6})(z|h|\/)',rest)
            	        if a:
            	            rest_name=a.group(1)
            	        if a.group(2)=='*':
            	            rest_alive=1
            	        else:
            	            rest_alive=0
            	        #print a.group(1), a.group(2) 
            	        rest=rest[18:]
            	        poschar=ord(rest[0:1])
            	        #print poschar
            	        
            	        if (poschar == 47 or poschar == 92 or (poschar >= 65 and poschar <= 90) or (poschar >= 97 and poschar <= 106)):
            	            #compressed
			    rest, symboltable, symbolcode, rest_lat, rest_lon, rest_course, rest_alt, rest_speed, rest_radiorange = self.compressed_to_decimal(rest)
            	            #rest=rest[13:]
            	           
            	        elif poschar >= 48 and poschar <= 57:
            	           #normal
			   rest_lat, rest_lon, symbolcode, symboltable=self.normalpos_to_decimal(rest)
			   rest=rest[19:]
			
            	        #continue here
            	        if symbolcode <> '_':
			    rest, rest_course, rest_speed, rest_alt = self.comment_to_decimal(rest,rest_course, rest_speed, rest_alt)
			    
			    
			    
			    if len(rest)>0:
			        rest_comment=rest    
	
            	            
            	    
		#NMEA
            elif packettype == '$':
		    rest_comment="NMEA, parse later"
		    #print "nmea", fromcall
		#item
            elif packettype == ')':
            	    #pass
            	    rest_type='item'
            	    if len(rest)>=18:
            	    	a=re.search('^\)([\x20\x22-\x5e\x60-\x7e]{3,9})(!|_)',rest) 
            	    	if a:
            	            rest_name=a.group(1)
            	        if a.group(2)=='!':
            	            rest_alive=1
            	        else:
            	            rest_alive=0
            	    #	print data
            	    rest= rest[2 + len(rest_name):]
            	    poschar=ord(rest[0:1])
            	    #print poschar
            	        
		    if (poschar == 47 or poschar == 92 or (poschar >= 65 and poschar <= 90) or (poschar >= 97 and poschar <= 106)):
		        #compressed
		        rest, symboltable, symbolcode, rest_lat, rest_lon, rest_course, rest_alt, rest_speed, rest_radiorange = self.compressed_to_decimal(rest)
		        #rest=rest[13:]
		   
		    elif poschar >= 48 and poschar <= 57:
		       #normal
		       rest_lat, rest_lon, symbolcode, symboltable=self.normalpos_to_decimal(rest)
		       rest=rest[19:]
		
		    #continue here
		    if symbolcode <> '_':
		        rest, rest_course, rest_speed, rest_alt = self.comment_to_decimal(rest,rest_course, rest_speed, rest_alt)
		        if len(rest)>0:
			    rest_comment=rest 
	    
	    
            	    
		#status
            elif packettype == '>':
            	    rest_type='station'
		    if re.search('^\d{6}z',rest[1:]):
			rest_status=rest[8:].replace('\r\n', ' ')
		    else:
			rest_status=rest[1:]
		    #print "status: ", rest_status
		#something else
            else:
		    pass
            
            #print "comment: ", rest_comment
	    #print rest_speed, rest_course, rest_lat, rest_lon
            global STATION_LIST
            # STATION_LIST structure:
            # STATION,( buble0, text1, first seen2, last seen3, status4,speed5, course6,lat7,lon8,comment9,packet count10,distance11,text label12)
            # temporary structure: first seen, last seen, packet
            #now = time.strftime("%H:%M", time.localtime())
            #print rest
	    coordinates=self.main.aprs.get_position("distance")
	    #print coordinates
	    
	    callsign=fromcall
	    if (rest_type == 'object' or rest_type == 'item') and rest_name<>'':
	    	callsign=rest_name
	    #print "test2: ", fromcall, rest_speed
	    if callsign in STATION_LIST:
			#print "Update existing station: ", fromcall
			STATION=STATION_LIST[callsign] #get previous values
			if rest_status=='':
				rest_status=STATION[4]
			if rest_speed=='':
				print "speed updated from %s to %s" %(rest_speed,STATION[5])
				rest_speed=STATION[5]
			if rest_course=='':
				rest_course=STATION[6]
			if rest_lat=='':
				rest_lat=STATION[7]
			if rest_lon=='':
				rest_lon=STATION[8]
			if rest_comment=='':
				rest_comment=STATION[9]
			if rest_alt=='':
				rest_alt=STATION[14]
			if rest_type=='':
				rest_type=STATION[15]
			if rest_alive=='':
				rest_alive=STATION[17]
			if symbolcode=='':
				symbolcode=STATION[18]
			if symboltable=='':
				symboltable=STATION[19]
				
				
				
				
				
			#if STATION[11]:
			#	rest_tex=STATION[11]
			#else:
			#	rest_tex=''
			if rest_type == 'station':
			    STATION_LIST[fromcall]=[STATION[0],STATION[1],STATION[2],time.time(),rest_status,rest_speed,rest_course,rest_lat,rest_lon,rest_comment,STATION[10]+1,STATION[11],STATION[12],STATION[13],rest_alt, rest_type,rest_name, rest_alive, symbolcode, symboltable]
			    
			if rest_type == 'object' or rest_type == 'item':
			    STATION_LIST[rest_name]=[STATION[0],STATION[1],STATION[2],time.time(),rest_status,rest_speed,rest_course,rest_lat,rest_lon,rest_comment,STATION[10]+1,STATION[11],STATION[12],STATION[13],rest_alt, rest_type,fromcall, rest_alive, symbolcode, symboltable]
			    fromcall=rest_name
			# update station to the list
			#    def update_station(self, bubble, firstseen, lastseen, msgtext, *args, **kargs):
			#print time.localtime(), time.strptime(STATION[2],"%H:%M")
			if not STATION[12]: #blocked? 0/1
			    #not blocked, then update
			    if not STATION[13]:#hidden? 0/1
			    	#not hidden, just update
			        self.main.stations_page.update_station(STATION_LIST[fromcall][0],fromcall,coordinates)
			        #print "updating station ", fromcall
			        if VIEW_STATION == fromcall:
			            #print "new packet for watched ", fromcall
			            self.main.station_details_page.prepare_show_station_details(self,VIEW_STATION, coordinates, None)
			    else:
			    	#was hidden, need to recreate:
			    	but,tex=self.main.stations_page.render_station_button(fromcall)
			    	STATION_LIST[fromcall][0]=but
			    	STATION_LIST[fromcall][11]=tex
			    	STATION_LIST[fromcall][13]=0
			    	
		    	else:
		    		pass
				#print "Ignore blocked station: ", fromcall
	    else: # add new station
		#print "Add new station: ", fromcall
		#STATION_LIST[fromcall]=['buble',now, now, rest]
		#print "STATION_LIST[%s]=[%s,%s,%s]" % (fromcall,now,now,rest)
		# repopulate list of stations
		#                                   self, callsign, timestamp, msgtext, rest_speed, rest_course, rest_lat, rest_lon, rest_comment,rest_distance, *args, **kargs)
    	        if rest_speed == '':
    	            rest_speed=0
    	        
		if rest_type == 'object' or rest_type == 'item':
		    STATION_LIST[rest_name]=[0,rest_name,time.time(), time.time(), rest_status,rest_speed,rest_course,rest_lat,rest_lon,rest_comment,1,0,0,0,rest_alt, rest_type,fromcall, rest_alive,symbolcode, symboltable]
		    but,tex=self.main.stations_page.render_station_button(rest_name)
		    STATION_LIST[rest_name][0]=but
		    STATION_LIST[rest_name][11]=tex
		    self.main.stations_page.update_station(STATION_LIST[rest_name][0],rest_name,coordinates)


		else:
		    STATION_LIST[fromcall]=[0,fromcall,time.time(), time.time(), rest_status,rest_speed,rest_course,rest_lat,rest_lon,rest_comment,1,0,0,0,rest_alt, rest_type,rest_name, rest_alive,symbolcode, symboltable]
		    but,tex=self.main.stations_page.render_station_button(fromcall)
		    STATION_LIST[fromcall][0]=but
		    STATION_LIST[fromcall][11]=tex
		    self.main.stations_page.update_station(STATION_LIST[fromcall][0],fromcall,coordinates)


            #print STATION_LIST
            
    def choose(self, a, b, *xargs):
    	for i in a, b:
    	    if i:
    	    	print i
    		return i	
            
    def b90(self):
        if (self.sequence > 8099):
            self.sequence = 0
        first = ((self.sequence / 90) % 90) + 33
        second = (self.sequence % 90) + 33
        output = "%c%c" % (first, second)
        self.sequence += 1
        return output

    def msg_queue(self, call, sequence, message):
        if (len(self.message_list) >= MAX_MSG_QUEUE):
            self.main.main_page.status_write("Too many messages in queue.\n")
            return False
        id = "%s-%s" % (call, sequence)
        if (call in self.queue_list):
            if (len(self.queue_list[call]) >= MAX_PER_CALL_QUEUE):
                self.main.main_page.status_write("Too many messages to %s in queue.\n" % call)
                return False
            self.queue_list[call].append(sequence)
            self.message_list[id] = message
        else:
            self.queue_list[call] = []
            self.queue_list[call].append(sequence)
            self.message_list[id] = message
        self.main.main_page.status_write("%s To:%s> %s <-queued->\n" % (time.strftime("%m/%d %H:%M", time.localtime()), call, message))
        # if a message is received before the next lines are run there will be problems...
        #iter = self.messagebuffer.get_iter_at_line(self.messagebuffer.get_line_count() - 2)
        #iter.forward_chars(15 + len(call))
        #self.message_marks[id] = self.messagebuffer.create_mark(None, iter, True)
	#self.message_marks[id].set_visible(True)

        #bold_end = iter.copy()
        #bold_start = iter.copy()
        #bold_end.forward_to_line_end()
        #bold_end = bold_end.backward_search("<", gtk.TEXT_SEARCH_TEXT_ONLY)
        #bold_start.forward_chars(2)
        #self.messagebuffer.apply_tag(self.messagebold, bold_start, bold_end[0])

        return True

    def send_msg_queue(self, call, count=2, delay=7, start_timer=True):
        if (call in self.queue_list):
            if (self.queue_list[call] == []):
                del self.queue_list[call]
                return False

            sequence = self.queue_list[call].pop(0)
            id = "%s-%s" % (call, sequence)
            message = self.message_list[id]
            del self.message_list[id]

            # record this so cancel can work on current messages
            self.current_message[call] = sequence

            # record this so clear can re-add current messages
            self.current_message_text[call] = message

            # save count and delay for the clear button
            self.current_message_count[call] = count
            self.current_message_delay[call] = delay

            # send message
            isbulletin = self.bulletin_check(call)
            if (start_timer):
                if (isbulletin):
                    packet=":%s:%s" % (call.ljust(9), message)
                    #self.msg_check(path+packet)
                    self.send_data(packet)
                    #gobject.timeout_add(600 * 1000, self.msg_timer, call, message, sequence, count, 600)
                    #gobject.timeout_add(600 * 1000, self.msg_timer, call, message, sequence, count, 600)
		    ecore.timer_add(600*100, self.msg_timer, call, message, sequence, count, 600) #ecore glib call
                else:
                    replyack = self.replyack(call)
                    packet=":%s:%s{%s}%s" % (call.ljust(9), message, sequence, replyack)
                    #self.msg_check(path+packet)
                    self.send_data(packet)
                    self.recv_acks["%s-%s" % (call, sequence)] = 0
                    #gobject.timeout_add(delay * 1000, self.msg_timer, call, message, sequence, count, delay)
                    #gobject.timeout_add(delay * 1000, self.msg_timer, call, message, sequence, count, delay)
		    ecore.timer_add(delay * 100, self.msg_timer, call, message, sequence, count, delay) #ecore glib call


    def replyack(self, tocall):
        replyack = ""
        if (tocall in self.sent_acks):
            id = "%s-%s" % (tocall, self.sent_acks[tocall])
            if (time.time() - self.sent_acks[id] < 5400):
                # less than 90 minutes ago
                replyack = self.sent_acks[tocall]
        return replyack


    def msg_timer(self, tocall, message, sequence, count, delay):
        id = "%s-%s" % (tocall, sequence)
        if (self.recv_acks[id] == 1):
            return False
        else:

            isbulletin = self.bulletin_check(tocall)
            if (isbulletin):
                self.send_data(":%s:%s" % (tocall.ljust(9), message))
            else:
                replyack = self.replyack(tocall)
                self.send_data(":%s:%s{%s}%s" % (tocall.ljust(9), message, sequence, replyack))

            # start the next timer
            count += 1
            if (count > MAXRETRIES):
                self.recv_acks[id] = 1

                self.send_msg_queue(tocall)
                return False
            delay *=  2
            if (delay > 600):
                delay = 600
            #gobject.timeout_add(delay * 1000, self.msg_timer, tocall, message, sequence, count, delay)
	    ecore.timer_add(delay * 100, self.msg_timer, tocall, message, sequence, count, delay) #ecore glib call

            # save count and delay for the clear button
            self.current_message_count[tocall] = count
            self.current_message_delay[tocall] = delay

            # and stop this timer
            return False


    def send_message(self, tocall=None, message=None, sequence=None, count=2, delay=7, start_timer=True):
    #self.send_message(None, label_callsign , label_text, sequence, count, delay, False)
        sendnow = False
        tocall = tocall.upper()
        
        if (message == ""):
            return False

        isbulletin = self.bulletin_check(tocall)

        # check for illegal characters before clearing message
        if (isbulletin):
            if (message.find("|") != -1 or message.find("~") != -1):
                self.message_write("Bulletins can not contain the following characters: | ~")
                return False
        else:
            if (message.find("|") != -1 or message.find("~") != -1 or message.find("{") != -1):
                self.message_write("Messages can not contain the following characters: | ~ {")
                return False

        # add callsign to list if just entered
        #if (self.last_selected != tocall):
        #    self.add_callsign(tocall, True)

        # get a sequence number
        if (sequence == None):
            sequence = "%s" % self.b90()

        # in case clear window is called:
        id = "%s-%s" % (tocall, sequence)
        self.recv_acks[id] = 0

        # TODO
        # cancel message option - menu popup

        # is there a queue for this callsign?
        if (tocall not in self.queue_list):
            sendnow = True

        # add the message to the queue
        if (not self.msg_queue(tocall, sequence, message)):
            if (self.sequence > 0):
                self.sequence -= 1
            return False

        # clear the message text box
        #self.messagetext.set_text("")

        if (sendnow):
            self.main.notify_show("Send message to " + tocall + " ", 3)
            self.send_msg_queue(tocall, count, delay, start_timer)
            


    def bulletin_check(self, callsign):
        # hard code CQSRVR
	#self.status_write(callsign)
	if (callsign == "CQSRVR"):
            return False
        for currentcall in self.bulletins:
            length = len(currentcall)
            if (currentcall == callsign[:length]):
                return True
        return False

    def istodisplay_check(self, callsign, to_whom):
        # hard code ALL
	#print "is to display? ", callsign
	#print "to whom", to_whom
	self.main.main_page.status_write(callsign)
	if (to_whom[0] == "ALL"):
	    #print "ALL"
            return True
        for currentcall in to_whom:
            length = len(currentcall)
            if (currentcall == callsign[:length]):
		print "was in list"
                return True
	print "no luck in is to display"
        return False




    def track(self):
            #global action
            if action == "stopit":
            	    #self.main.main_page.toggle.state_set(False)
            	    pass
            elif action == "run":
                    self.run()
                    
            return 0
            
    def blink():
            pass

    def track_status(self):
            #global action
            if action == "stopit":
            	    pass
            elif action == "run":
                    self.run_status()
                    

    def run_status(self):
    	    self.main.preferences_page.send_status()
    	    ecore.timer_add(900, self.track_status) #600

    def track_maintenance(self):
            if self.main.main_page.toggle_con.state_get():
                    self.run_maintenance()
            else:
            	    pass


    def run_maintenance(self):
    	    #print "running maintenance", VIEW_STATION
    	    coordinates=self.main.aprs.get_position("distance")
    	    #print coordinates
            for i in STATION_LIST.keys():
                if not STATION_LIST[i][13]:
                    self.main.stations_page.update_station(STATION_LIST[i][0],STATION_LIST[i][1],coordinates)
                    
            if VIEW_STATION <> "":
            	self.main.station_details_page.prepare_show_station_details(self,VIEW_STATION, coordinates, None)
    	
    	    ecore.timer_add(60, self.track_maintenance) #60

    def run(self):
	    self.send_now()		
	    self.main.main_page.status_write ("Delay %s" % delay_send) 
            x=ecore.timer_add(delay_send, self.track)
            #print x
                    
    def send_now(self):
	    global delay_send
            pac_new=self.get_position()
	    if (pac_new == "nofix"): #if no fix, try later
		delay_send=5
		self.main.main_page.status_write ("No fix %s" % time.strftime('%H:%M:%S',time.localtime(time.time()))) 
	    else: #send now
		delay_send=delay_user
		global force_send    
		global unique_packet_old
                global now_old
                global heading_old
                now_diff=now-now_old #gps_time - old time
		print "now diff", now_diff
		
                if unique_packet_old == unique_packet_new or now_diff < delay_minimum and force_send != 1:
            	    #not too often? except if forced
            	    #print "too often! or duplicated packet###############"
                    self.main.main_page.status_write("Place/time < %s" % delay_minimum)
                    delay_send=8 #try in 8 secs again
                            
                else: # send the packet and set some values to remmember
            	    #print "packet finally ok *****************"
                    unique_packet_old = unique_packet_new # remember the packet
                    now_old = now #time
                    heading_old = int(heading_now)
		    force_send=0
                    #print "set heading", heading
                    #print 'set time', now_old
		    self.main.main_page.status_write ("SENDING %s" % time.strftime('%H:%M:%S',time.localtime(time.time()))) 
		    
		    if __aprs_enable__:
		    	try:
			    self.sock.sendall(pac_new) #calling sending of packet here
			except:
			    status = "NO NETWORK"
			    self.main.main_page.status_write(status)
			    self.reconnect()
		
		    #youloc test here:
		    if __youloc_enable__:
			api_url = 'http://youloc.net/logger.php'
			self.opener = urllib2.build_opener()
			self.opener.addheaders = [('User-agent', ('Lokatin/%s/%s' % (appversion,appname)))]
			#print "get params"
			params=self.get_position('youloc')
			#print "parametry: ", params
			url = api_url + '?' + urllib.urlencode(params)
			try:
			  u = self.opener.open(url, None, 10)
			except urllib2.HTTPError, e:
			  self.main.main_page.status_write('%s: %s' % (e, e.readline()))
			  
		return 0      
    
    def conv_1(self, ilat, ilon):

        templat = float(ilat.replace(',', '.'))
        templon = float(ilon.replace(',', '.'))
	print templat, templon
        degLat = int(templat)
        minDezLat =(templat-degLat)*60
        minLat = int(minDezLat)
        sekLat = ((templat-degLat)*60-minLat)*60
        minLat = abs(minLat)
        minDezLat = abs(minDezLat)
        sekLat = abs(sekLat)
        degLon = int(templon)
        minDezLon = (templon-degLon)*60
        minLon = int(minDezLon)
        sekLon = ((templon-degLon)*60-minLon)*60
        minLon = abs(minLon)
        minDezLon = abs(minDezLon)
        sekLon = abs(sekLon)
	#normal packet
        #if minDezLon < 10:
        #    minDezLon = '0' + str(minDezLon)
        #normal packet   
        #if minDezLat < 10:
        #    minDezLat = '0' + str(minDezLat)

	return degLat, minDezLat, degLon, minDezLon

    def compress_lat(self, deg):
	temp = abs(int(380926 * (90 - (deg))))
	#print "temp lon",  temp
	lat_0 = chr(temp/91**3 + 33)
	temp = temp%91**3
	lat_1 = chr(temp/91**2 + 33)
	temp = temp%91**2
	lat_2 = chr(temp/91 + 33)
	temp = temp%91
	lat_3 = chr(temp + 33)
	#print lat, lat_1, lat_2, lat_3
	return lat_0, lat_1, lat_2, lat_3

    def compress_lon(self,deg):
	temp = abs(int(190463 * (180 + (deg))))
	#print "temp lat",  temp
	lon_0 = chr(temp/91**3 + 33)
	temp = temp%91**3
	lon_1 = chr(temp/91**2 + 33)
	temp = temp%91**2
	lon_2 = chr(temp/91 + 33)
	temp = temp%91
	lon_3 = chr(temp + 33)
	#print lon, lon_1, lon_2, lon_3
	return lon_0, lon_1, lon_2, lon_3


    def compressed_to_decimal(self, packet, *xargs):
    	    
    	    symboltable=''
    	    symbolcode=''
    	    rest_lat=''
    	    rest_lon=''
    	    rest_course=''
    	    rest_alt=''
    	    rest_speed=''
    	    rest_radiorange=''
    	    
    	    symboltable = packet[0]
	    lat1 = ord(packet[1]) - 33
	    lat2 = ord(packet[2]) - 33
	    lat3 = ord(packet[3]) - 33
	    lat4 = ord(packet[4]) - 33
	    long1 = ord(packet[5]) - 33
	    long2 = ord(packet[6]) - 33
	    long3 = ord(packet[7]) - 33
	    long4 = ord(packet[8]) - 33
	    symbolcode = packet[9]
	    c1 = ord(packet[10]) - 33
	    s1 = ord(packet[11]) - 33
	    comptype = ord(packet[12]) - 33
	    
	    rest_lat=90-((lat1*91.0**3+lat2*91.0**2+lat3*91.0+lat4)/380926)
	    rest_lon=-180+((long1*91.0**3+long2*91.0**2+long3*91.0+long4)/190463)
	
	    packet=packet[13:]
	    # check the compression type, if GPGGA, then
	    # the cs bytes are altitude. Otherwise try
	    # to decode it as course and speed. And
	    # finally as radio range
	    # if c is space, then csT is not used.
	    # Also require that s is not a space.
	    if (c1 == -1 or s1 == -1):
		# csT not used
		pass
	    elif ((comptype & 0x18) == 0x10):
		# cs is altitude
		cs = c1 * 91 + s1
		# convert directly to meters
		rest_alt = round((1.002 ** cs) * 0.3048,0)
	    elif (c1 >= 0) and (c1 <= 89):
		if (c1 == 0):
		    # special case of north, APRS spec
		    # uses zero for unknown and 360 for north.
		    # so remember to convert north here.
		    rest_course = 360;
		else:
		    rest_course = c1 * 4
	
		# convert directly to km/h
		rest_speed = (1.08 ** s1 - 1) * 1.852
	    elif (c1 == 90):
		# convert directly to km
		rest_radiorange = (2 * 1.08 ** s1) * 1.609344
	    return packet, symboltable, symbolcode, rest_lat, rest_lon, rest_course, rest_alt, rest_speed, rest_radiorange

    	    
    	    

    def comment_to_decimal(self, packet,rest_course, rest_speed, rest_alt, *xargs):
    	#rest_course=''
    	#rest_speed=''
    	#rest_alt=''
    	
	if len(packet)>=7:
	    a=re.search('^([0-9. ]{3})\/([0-9. ]{3})',packet)
	    if a:
		rest_course=a.group(1)
		rest_speed=a.group(2)
		if re.search('^[0-9]{3}',rest_course): 
		    rest_course=int(rest_course)
		if re.search('^[0-9]{3}',rest_speed):
		    rest_speed=float(rest_speed)*1.852
		packet=packet[7:]
	a= re.search('^(.*?)\/A=(-\d{5}|\d{6})(.*)$',packet)
	if a:
	    # convert to meters as well
	    rest_alt = round(int(a.group(2)) * 0.3048,0);
	    packet = a.group(1) + a.group(3)

	return packet, rest_course, rest_speed, rest_alt
    
    
    # Parse a normal uncompressed location
    def normalpos_to_decimal(self, packet, *xargs):

	# Check the length
	#if (len(packet) < 19):
	#    print "packet too short"
	# Make a more detailed check on the format, but do the
	# actual value checks later
	lon_deg = ""
	lat_deg = ""
	lon_min = ""
	lat_min = ""
	issouth = 0
	iswest = 0
	symboltable=""
	symbolcode=""
	
	m = re.search('^(\d{2})([0-7 ][0-9 ]\.[0-9 ]{2})([NnSs])(.)(\d{3})([0-7 ][0-9 ]\.[0-9 ]{2})([EeWw])([\x21-\x7b\x7d])',packet)
	if m:
	    sind = m.group(3).upper();
	    wind = m.group(7).upper();
	    symboltable = m.group(4);
	    if (sind == 'S'):
	        issouth = 1;
		
	    if (wind == 'W'):
	        iswest = 1;
		
	    lat_deg = int(m.group(1))
	    lat_min = float(m.group(2))
	    lon_deg = int(m.group(5))
	    lon_min = float(m.group(6))
	    symbolcode=m.group(8)
	else:
	    print "error in normal to decimal"
	    
	#if not re.search('^[\/\\A-Z0-9]$/',symboltable)
	#	print "error in symboltable"
		
	
	# Check the degree values
	if (lat_deg > 89 or lon_deg > 179):
	    print "loc too large"
	    
	# Find out the amount of position ambiguity
	tmplat = str(lat_min);
	tmplat = tmplat.replace('.','') # remove the period
	# Count the amount of spaces at the end
	d = re.search('^(\d{0,4})( {0,4})',tmplat)
	if d:
	    posambiguity = len(d.group(2));
    	        
	latitude = "";
	longitude = "";
	if posambiguity == 0:
	    # No position ambiguity. Check longitude for invalid spaces
	    ##if (lon_min.find(''):
	    #???		
	    latitude = lat_deg + (lat_min/60);
	    longitude = lon_deg + (lon_min/60);
	elif posambiguity == 4:
	    # disregard the minutes and add 0.5 to the degree values
	    latitude = lat_deg + 0.5;
	    longitude = lon_deg + 0.5;
	elif posambiguity == 1:
	    # the last digit is not used
	    lat_min = lat_min[:4]
	    lon_min = lon_min[:4]
	    latitude = lat_deg + ((lat_min + 0.05)/60);
	    longitude = lon_deg + ((lon_min + 0.05)/60);
	elif posambiguity == 2:
	    # the minute decimals are not used
	    lat_min =lat_min[:2]
	    lon_min = lon_min[:2]
	    latitude = lat_deg + ((lat_min + 0.5)/60);
	    longitude = lon_deg + ((lon_min + 0.5)/60);
	elif posambiguity == 3:
	    # the single minutes are not used
	    lat_min = lat_min[:1] + '.5'
	    lon_min = lon_min[:1] + '.5'
	    latitude = lat_deg + (lat_min/60);
	    longitude = lon_deg + (lon_min/60);
	else:
	    print "error lat/lon..."

	# Finally apply south/west indicators
	if (issouth == 1):
		latitude = 0 - latitude;
	
	if (iswest == 1):
		longitude = 0 - longitude;
	
	# Store the locations
	# Calculate position resolution based on position ambiguity
	# calculated above.
	#$rethash->{'posresolution'} = _get_posresolution(2 - $rethash->{'posambiguity'});

	return latitude, longitude, symbolcode, symboltable


    def check_ax25call(self, components, *xargs):
    	    #print "components", components
    	    a=re.search('^([A-Z0-9]{1,6})(-\d{1,2}|)$',components)
    	    if a:
    	    	    if len(a.group(2))==0:
    	    	    	    return a.group(1)
    	    	    else:
    	    	    	    ssid=0-int(a.group(2))
    	    	    	    if ssid < 16 :
    	    	    	    	    return "%s-%s" % (a.group(1),ssid)
    	    	    
    
    def mice_to_decimal(self, packet, destcallsign, callsign, *xargs):
    	    
    	    mice_fixed=""
    	    rest_lat=''
    	    rest_lon=''
    	    rest_speed=''
    	    rest_alt=''
    	    rest_comment=''
    	    symbolcode=''
    	    symboltable=''
    	    
    	    symboltable=packet[7:8]
    	    destcallsign=destcallsign[:6]
    	    a=re.search(r'^[\x26-\x7f][\x26-\x61][\x1c-\x7f]{2}[\x1c-\x7d][\x1c-\x7f][\x21-\x7b\x7d][\/\\A-Z0-9]',packet)
	    if not a:
    	    	    a=packet=re.search(r'^([\x26-\x7f][\x26-\x61][\x1c-\x7f]{2})\x20([\x21-\x7b\x7d][\/\\A-Z0-9])(.*)/$1\x20\x20$2$3',packet)
    	    	    if a:
    	    	    	    mice_fixed=1
    	    	    else:
    	    	    	    return 0,0,0,0,0,0,0
    	    
    	    tmplat=destcallsign
    	    translation=maketrans('ABCDEFGHIJPQRSTUVXXYKLZ',
                                  '01234567890123456789___')
            tmplat=tmplat.translate(translation)
            a=re.search('^(\d+)(_*)$',tmplat)
            if a:
            	    amount=6-len(a.group(1))
            	    if amount >4:
            	    	    return 0,0,0,0,0,0,0
            	    	    
		    posambiguity=amount
		    #print "ambi: ", posambiguity
		    posresolution=1.852 * 1000 * 10 ** (-1 * (2 - amount))
		    
	    else:
	    	    return 0,0,0,0,0,0,0
            	    	    
            	    	    
	    if posambiguity >=4:	    
    	    	   tmplat=tmplat.replace('_','3',1)
    	    else:
    	    	   tmplat=tmplat.replace('_','5',1)
    	    	   
    	    tmplat=tmplat.replace('_','0')
    	    latdeg=int(tmplat[:2])
    	    #print "latdeg", latdeg
    	    latmin=float("%s.%s" %(tmplat[2:4],tmplat[4:6]))
    	    #print "latmin", latmin
    	    rest_lat=latdeg+(latmin/60)
    	    #print rest_lat
    	    nschar=ord(destcallsign[3:4])
    	    if nschar <= 0x4c:
    	    	    rest_lat=0-rest_lat
	    #print rest_lat
    		
    	    mbitstring=destcallsign[:3]
    	    translation=maketrans('0123456789LPQRSTUVWXYZABCDEFGHIJK',
                                  '000000000001111111111122222222222')
            mbitstring=mbitstring.translate(translation)
    	    mbits=mbitstring
    	    
    	    lon=ord(packet[:1]) - 28
    	    #print "1: ", lon
    	    longoffsetchar=ord(destcallsign[4:5])
    	    if longoffsetchar >=0x50:
    	    	    lon=lon+100
    	    #print "2: ", lon
	    if lon >=180 and lon <= 189:
	    	    lon=lon-80
	    elif lon >=190 and lon <=199:
	    	    lon=lon-190
	    #print "3: ", lon	    	    
	    lonmin=ord(packet[1:2]) - 28
	    if lonmin >= 60:
	    	    lonmin=lonmin-60
	    lonmin="%02d.%02d" % (lonmin,ord(packet[2:3]) - 28)
    	    if posambiguity == 4:
    	    	    lon=lon+0.5
    	    elif posambiguity == 3:
    	    	    lontmp=lonmin[:1]+'5'
    	    	    lon=lon+float(lonmin)/60
    	    elif posambiguity == 2:
    	    	    lontmp=lonmin[:2]+'.5'
    	    	    lon=lon+float(lonmin)/60
    	    elif posambiguity == 1:
    	    	    lontmp=lonmin[:4]+'5'
    	    	    lon=lon+float(lonmin)/60
    	    elif posambiguity == 0:
    	    	    lon=lon+float(lonmin)/60
    	    else:
    	    	    return 0
    	    	    
    	    #print destcallsign
	    rest_lon=lon
	    ewchar=ord(destcallsign[5:6])
   	    if ewchar >= 0x50:
    	    	    rest_lon=0-rest_lon
	    #print rest_lon
	    
	    # Now onto speed and course
	    speed = (ord(packet[3:4]) - 28) * 10
	    coursespeed = ord(packet[4:5]) - 28
	    coursespeedtmp = int(coursespeed / 10)
	    speed += coursespeedtmp
	    coursespeed -= coursespeedtmp * 10
	    course = 100 * coursespeed
	    course += ord(packet[5:6]) - 28
	    # do some important adjustements
	    if (speed >= 800):
	    	    speed -= 800
	    if (course >= 400):
	    	    course -= 400
	
	    # convert speed to km/h and store
	    rest_speed = speed * 1.852
	    #print "speed ", rest_speed
	    # also zero course is saved, which means unknown
	    if (course >= 0):
	    	    rest_course=course
	    	    #print "course ", rest_course
	    	    
	    # save the symbol table and code
	    symbolcode = packet[6:7]
	    symboltable = symboltable

	    #TODO - decode alt and comment
	    
	    if len(packet)>8:
	    	    rest=packet[8:]
	    	    a=re.search('^(.*?)([\x21-\x7b])([\x21-\x7b])([\x21-\x7b])\}(.*)$',rest)
	    	    if a:
	    	    	    	rest_alt = (
				(ord(a.group(2)) - 33) * 91 ** 2 +
				(ord(a.group(3)) - 33) * 91 +
				(ord(a.group(4)) - 33)) - 10000;
				rest = a.group(5)
				#print "alt ", rest_alt
		    if len(rest)>0:
		    	    rest_comment="Mic-E test: " + rest
		    	    #print "comment ", rest_comment
    	    return rest_lat, rest_lon, rest_speed, rest_alt, rest_comment, symbolcode, symboltable
    		
resources=getResources()	

class MainWindow:

    def getConfig(self):
    	global __conffile__
    	cfg_dir = os.path.join(os.path.expanduser("~"), ".config/%s" % appname.lower())
        if not os.path.exists(cfg_dir):
            os.makedirs(cfg_dir, 0755)
            
	__conffile__ = os.path.join(cfg_dir, '%s.conf' % appname.lower())
	default_cfg = os.path.join(DATA_DIR, '%s.conf' % appname.lower())
	
        if not os.path.exists(__conffile__):
            if os.path.exists(default_cfg):
                shutil.copy2(default_cfg,__conffile__)
            else:
            	print "config file doesn't exist, default config doesn't exist"
    	    
        global config
        global username, comment, password, aprsstatus,path
        global delay_user, serverhost, serverport, aprsfilter, timeout
        global home_qth, aprs_symbol, aprs_table_overlay, serverPort, serverHost
        global __youloc_enable__, __youloc_userkey__,__aprs_enable__
        global TEMPLATE_LIST, CALLER_LIST, OBJECT_LIST
        global OLD_POSITION
        TEMPLATE_LIST=[]
        CALLER_LIST=[]
        OBJECT_LIST=[]
        
        config = ConfigParser.ConfigParser()
        config.read(__conffile__)

        __youloc_enable__ = config.get("youloc", "enable")
        __youloc_userkey__ = config.get("youloc", "userkey")
        
        __aprs_enable__ = config.get("aprs", "enable")
        aprsfilter = config.get("aprs", "filter")
        timeout = config.getint("aprs", "timeout")
        aprsstatus = config.get("aprs", "aprsstatus")
        username = config.get("aprs", "username")
        password = config.get("aprs", "password")
        comment = config.get("aprs", "comment")
        serverHost = config.get("aprs", "serverhost")
        serverPort = config.getint("aprs", "serverport")
        aprs_table_overlay = config.get("aprs", "aprs_table_overlay")
        aprs_symbol = config.get("aprs", "aprs_symbol")
        home_qth = eval(config.get("aprs", "home_qth"))
        

	OLD_POSITION=[0,0,home_qth[0],home_qth[1],0]
	path = "%s>%s:" % (username,aprs_path)

	cnt=0
	for i in config.items('objects'):
	    x={'id'  : cnt,
	       'name': i[0],
	       'text': i[1]}
	    cnt=cnt+1
	    OBJECT_LIST.append(x)
	
	OBJECT_LIST=tuple(OBJECT_LIST)

	cnt=0
	for i in config.items('addressbook'):
	    x={'id'  : cnt,
	       'name': i[0],
	       'text': i[1]}
	    cnt=cnt+1
	    CALLER_LIST.append(x)
	    
	CALLER_LIST=tuple(CALLER_LIST)
	
	cnt=0
	for i in config.items('shorttext'):
	    x={'id'  : cnt,
	       'name': i[0],
	       'text': i[1]}
	    cnt=cnt+1
	    TEMPLATE_LIST.append(x)
	    
	
	TEMPLATE_LIST=tuple(TEMPLATE_LIST)

	rotation = config.getboolean("general", "rotation")
	self.win.rotation_set(rotation * 90)

	fullscreen = config.getboolean("general", "fullscreen")
	self.win.fullscreen_set(fullscreen)

	cpu = config.getboolean("general", "cpu")
        if cpu:
            try:
	        resources.usage_iface.RequestResource("CPU")
	    except:
	    	pass
	
        else:
            try:
	        resources.usage_iface.ReleaseResource("CPU") 
	    except:
	    	pass


	display = config.getboolean("general", "display")
	
    	if display:
            try:
    		resources.usage_iface.RequestResource("Display")
	    except:
	    	pass
    		
        else:
            try:
	        resources.usage_iface.ReleaseResource("Display") 
	    except:
	    	pass

	lightmode = config.getboolean("general", "lightmode")

        if lightmode:
            try:	
                resources.phonefso_iface.SetDefaultBrightness(30)
            except:
                print "error in brightnes"
        else:
            try:
                resources.phonefso_iface.SetDefaultBrightness(80)
            except:
                print "error in brightnes"

	

    def __init__(self):
	#window
            
	self.aprs=Aprs(self)
        self.win = elementary.Window('aTrack', elementary.ELM_WIN_BASIC)
        
        self.getConfig()
        
	self.win.title_set(str(username) + ' '+ str(appname) + ' ' + str(appversion))
        self.win.callback_destroy_add(self.destroy)

        bg = elementary.Background(self.win)
        self.win.resize_object_add(bg)
        bg.size_hint_weight_set(1, 1)# was 0 0
        bg.show()

        box = elementary.Box(self.win)
        self.win.resize_object_add(box)
        box.size_hint_weight_set(1, 1)
        box.show()

        # HACK HERE: put toolbar in a box to be able to scale it (75%)
        box_toolbar = elementary.Box(self.win)
        box_toolbar.scale_set(1)
        box_toolbar.size_hint_weight_set(1.0, 0)
        box_toolbar.size_hint_align_set(-1.0, 0)
        box_toolbar.show()

	global toolbar
        toolbar = elementary.Toolbar(self.win)
	toolbar.menu_parent_set(self.win)
	toolbar.homogenous_set(False)
	#toolbar.style_set(elementary.ELM_TOOLBAR_SHRINK_SCROLL)
        toolbar.size_hint_align_set(-1.0, 0)
        toolbar.show()

        self.toolbar_item_main = toolbar.item_append(
            '/usr/share/atrack/images/go-home.png', "Main", self.show_main_page)
        self.toolbar_item_card = toolbar.item_append(
            "/usr/share/atrack/images/emblem-system.png", "All", self.show_stations_page)
        self.toolbar_item_messages = toolbar.item_append(
            '/usr/share/atrack/images/mail-send-receive.png', "Msg", self.show_messages_page)
        #self.toolbar_item_create_message = toolbar.item_append(
            #Icon(self.win, 'mail-message-new.png'), "Write", self.show_create_message_page)
        self.toolbar_item_create_object = toolbar.item_append(
            '/usr/share/atrack/images/mail-message-new.png', "Make", self.show_create_object_page)
        self.toolbar_item_preferences = toolbar.item_append(
            '/usr/share/atrack/images/preferences.png', "Set", self.show_preferences_page)
        self.toolbar_item_about = toolbar.item_append(
            '/usr/share/atrack/images/about.png', "Abt", self.show_about_page)



        box_toolbar.pack_end(toolbar)
        box.pack_end(box_toolbar)

        self.pager = elementary.Pager(self.win)
        self.pager.size_hint_weight_set(1.0, 1.0)
        self.pager.size_hint_align_set(-1.0, -1.0)
        box.pack_end(self.pager)
        self.pager.show()

        self.preferences_page = PreferencesPage(self)
        self.messages_page = MessagesPage(self)
        self.create_message_page = CreateMessagePage(self)
        self.create_object_page = CreateObjectPage(self)
        self.stations_page = StationsPage(self)
        self.station_details_page = StationDetailsPage(self)
        self.about_page = AboutPage(self)
        #self.toolbar_item_main.selected=True
	#self.main_page.promote()
        self.main_page = MainPage(self)



	#self.toolbar_item_card.selected=True

	self.win.resize(480, 640)
        self.win.show()

	
    #def test_toolbar(self, *args):
	#toolbar.item_label_set(self.main.toolbar_item_main, "TEST")
	#self.toolbar_item_create_message.label("")


    def show_main_page(self, *args):
    	global VIEW_STATION
    	VIEW_STATION=''
        self.pager.content_promote(self.main_page.box)

    def show_preferences_page(self, *args):
        #self.toolbar_item_preferences.select()
        global VIEW_STATION
    	VIEW_STATION=''
        self.pager.content_promote(self.preferences_page.box)
 
    def show_about_page(self, *args):
    	global VIEW_STATION
    	VIEW_STATION=''
        self.pager.content_promote(self.about_page.box)

    def show_messages_page(self, *args):
    	global VIEW_STATION
    	VIEW_STATION=''
        self.pager.content_promote(self.messages_page.box)

    def show_create_message_page(self, *args):
    	global VIEW_STATION
    	VIEW_STATION=''
        self.pager.content_promote(self.create_message_page.box)
        
    def show_create_object_page(self, *args):
    	global VIEW_STATION
    	VIEW_STATION=''
        self.pager.content_promote(self.create_object_page.box)



    def show_stations_page(self, *args):
        self.pager.content_promote(self.stations_page.box)

    def show_station_details_page(self, *args):
        self.pager.content_promote(self.station_details_page.box)
        
    def kill_station_details_page(self, *args):
        self.pager.content_pop()
         

    def make_station_details(self, *xargs):
	self.station_details_page = StationDetailsPage(self)
    
    
    def destroy(self, *args, **kargs):
        """Called when closing window"""
        elementary.exit()

    def notify_close(self, *xargs):
        self.notify.hide()

    def notify_show(self,text, tmout=''):
        self.notify = elementary.Notify(self.win)
	self.notify.repeat_events_set(False)
	if not tmout: tmout=1
	self.notify.timeout_set(tmout)                                      
	self.notify.orient_set(elementary.ELM_NOTIFY_ORIENT_LEFT)                                  
			                                       
	bx = elementary.Box(self.win)                                   
	#bx.size_hint_weight_set(evas.EVAS_HINT_EXPAND, evas.EVAS_HINT_EXPAND)
	bx.horizontal_set(True)
	self.notify.content_set(bx)
	bx.show()

	lb = elementary.Label(self.win)
	lb.label_set(text)
	bx.pack_end(lb)
	lb.show()

	bt = elementary.Button(self.win)
	bt.label_set("Close")
	bt.callback_clicked_add(self.notify_close)
	bx.pack_end(bt)
	bt.show()
	self.notify.show()



def main ():
    elementary.init()
    #print os.path.join(DATA_DIR, 'atrack.edj')
    elementary.theme_overlay_add(os.path.join(DATA_DIR, 'atrack.edj'))
    win = MainWindow()
    elementary.run()
    elementary.shutdown()
    return 0


if __name__ == "__main__":
    exit(main())



